8

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?

kapa
  • 77,694
  • 21
  • 158
  • 175
fabb
  • 11,660
  • 13
  • 67
  • 111

3 Answers3

9

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';
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Thank you a lot! I tried that but it would not work, so I thought it was due to the nodeset not being live. But actually I just forgot to initialize the iterator (=0)... – fabb Jun 11 '11 at 09:28
5

this will also work..

[].forEach.call(document.querySelectorAll('div.foo'), function (el) {
    el.style.color = 'blue';
});
shunryu111
  • 5,895
  • 4
  • 27
  • 16
  • Its interesting to me that the above works, but `document.querySelectorAll('div.foo').forEach(function (e1) ...` doesn't work. Any ideas why? – Rene Wooller Jan 29 '15 at 03:51
  • 1
    querySelectorAll returns a NodeList, which doesn't have forEach. See: https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F – seans Feb 24 '15 at 15:44
1

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