querySelectorAll: manipulating nodes

馋奶兔 提交于 2019-12-05 03:28:39

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';
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!