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

javascript - querySelectorAll: manipulating nodes - Stack Overflow

programmeradmin2浏览0评论

As far as I have understood, querySelector returns a real changeable element while querySelectorAll returns a non-live Static Node Set.

I want to adjust the style of all elements fitting to a specific selector. It works fine for the first element with querySelector, but not for all matching elements with querySelectorAll. I guess that's because the node set is non-live.

Is there a workaround? Or am I missing something?

As far as I have understood, querySelector returns a real changeable element while querySelectorAll returns a non-live Static Node Set.

I want to adjust the style of all elements fitting to a specific selector. It works fine for the first element with querySelector, but not for all matching elements with querySelectorAll. I guess that's because the node set is non-live.

Is there a workaround? Or am I missing something?

Share Improve this question edited Jun 10, 2011 at 17:17 kapa 78.7k21 gold badges164 silver badges177 bronze badges asked Jun 10, 2011 at 17:12 fabbfabb 11.7k13 gold badges72 silver badges115 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

The problem is that querySelector returns a single node. querySelectorAll returns a set of nodes (the live-ness means the elements in the set won't be removed if you update them). You need to set a style on each of the elements matched, probably with a loop -- you can't just set a property once for all of them.

So, you probably need to do something like this:

var nodes = document.querySelectorAll('div.foo');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].style.color = 'blue';
}

this will also work..

[].forEach.call(document.querySelectorAll('div.foo'), function (el) {
    el.style.color = 'blue';
});

As described in querySelectorAll: manipulating nodes but with a way to make it work, since forEach only works on Arrays, not on NodeLists:

Array.prototype.slice.call(document.querySelectorAll('div.foo')).forEach(function(el) {
    el.style.color = 'blue';
});
发布评论

评论列表(0)

  1. 暂无评论