With my little knowledge of JavaScript, I'm trying to remove the href links on the name and title text when hovering over an image: /
What I thought would work:
document.querySelectorAll("h3.the-title a, div.portfolio-categories a").removeAttribute("href");
Only seems to actually work when given an array value:
document.querySelectorAll("h3.the-title a, div.portfolio-categories a")[0].removeAttribute("href");
Which, by logic, only does the first instance.
Why is it not allowing me to disable all links with the first method?
With my little knowledge of JavaScript, I'm trying to remove the href links on the name and title text when hovering over an image: http://www.equiuspartners./site/our-team/
What I thought would work:
document.querySelectorAll("h3.the-title a, div.portfolio-categories a").removeAttribute("href");
Only seems to actually work when given an array value:
document.querySelectorAll("h3.the-title a, div.portfolio-categories a")[0].removeAttribute("href");
Which, by logic, only does the first instance.
Why is it not allowing me to disable all links with the first method?
Share Improve this question asked Feb 11, 2016 at 21:45 TannieTannie 511 silver badge4 bronze badges 1- because collections do not have those methods. – epascarello Commented Feb 11, 2016 at 21:48
2 Answers
Reset to default 5querySelectorAll
returns a nodeList, an array-like object containing all the elements that could be a match for the given selector, not a single element.
You'd have to iterate to remove the attribute on all those elements
var elems = document.querySelectorAll("h3.the-title a, div.portfolio-categories a");
for (var i=0; i<elems.length; i++) {
elems[i].removeAttribute("href");
}
That's how it is, document.querySelectorAll()
returns a collection, not a single element. In modern browsers, you can use this to remove all attributes from all matched elements:
Array.from(document.querySelectorAll(<selector>))
.forEach(e => e.removeAttribute('href'));
Please note that you can use arrow functions
and Array.from()
in latest chrome and firefox only, (though there's a polyfill for Array.from available at above link.)