最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Removing Attribute - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

发布评论

评论列表(0)

  1. 暂无评论