Javascript code

Javascript: Loop over querySelectorAll without error

In Javascript, there are a lot of instances when you want to find multiple elements on a page to apply a common operation to all of them.

Suppose you want to hide elements of a particular class present on your web page. To do this, first get an array of all such elements using querySelectorAll and then loop through that array items to change the display property of all such elements.

But there is an issue. querySelectorAll also returns additional data, a static NodeList. If you iterate through all the items, you will hit the static NodeList which will give error.

So, what is the solution for this?

First, find the number of elements found matching the given selector using length property. Then use a for loop and iterate upto length number of items.

This will be more clear through following code example.

// Let's assume that we are looking for all elements with class "demo-item"
elements = document.querySelectorAll( '.demo-item' );
var i = 0;
for ( i = 0; i < elements.length; i++ ) {
elements[i].style.display = "none";
}

Hope this helps.

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *