Other loops such as for, map, etc only work with arrays and to make them work with NodeList, we have to convert it into an array by using the Array.from() method.
In the following example, we have multiple div elements. We will check if there is an element with a class of change. If yes, we will change its background color to red. If not, then will change the background color of the 3rd div element to red. Please have a look over the code example and the steps given below.
HTML & CSS
We have multiple div elements in the HTML file. The div element with a class of container is just a wrapper for the rest of the elements.
We have done some basic styling using CSS and added the link to our style.css stylesheet in the head element.
We are using the querySelector() method to select div element with a class of change and also we are using the querySelectorAll() method to select all div elements except the div element with a class of container.
You can see we are using the logical OR (||) operator here. This simply means if querySelector() method returns null, then execute querySelectorAll() method. We are storing the returned value in the element variable.
We are using the if statement and instanceof operator to verify whether the element variable holds a NodeList or not. Depending upon the result, we will change the background color of either the first div element or the third div element to red.