Tannie
Tannie

Reputation: 51

Removing Attribute

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.com/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?

Upvotes: 3

Views: 4612

Answers (2)

baao
baao

Reputation: 73211

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.)

Upvotes: 4

adeneo
adeneo

Reputation: 318182

querySelectorAll 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");
}

Upvotes: 5

Related Questions