Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelectorAll: manipulating nodes

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?

like image 878
fabb Avatar asked Jun 10 '11 17:06

fabb


People also ask

What does the querySelectorAll () method do?

Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

What is the difference between getElementsByClassName and querySelectorAll?

About the differences, there is an important one in the results between querySelectorAll and getElementsByClassName : the return value is different. querySelectorAll will return a static collection, while getElementsByClassName returns a live collection.

Why do we use querySelectorAll?

The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method.

How does the querySelector () method differ from querySelectorAll ()?

document. querySelector(selectors); It returns the first element which matches the selector. querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s).


2 Answers

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';
}
like image 160
lonesomeday Avatar answered Sep 22 '22 00:09

lonesomeday


this will also work..

[].forEach.call(document.querySelectorAll('div.foo'), function (el) {
    el.style.color = 'blue';
});
like image 25
shunryu111 Avatar answered Sep 21 '22 00:09

shunryu111