How to Detect NodeList in Javascript
In this tutorial, you will learn how to detect NodeList in javascript. A NodeList is a collection of document nodes. It looks like an array and we can iterate over it with the help of the forEach()
loop.
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 javascript, the querySelector()
method returns a single node and querySelectorAll()
method returns a NodeList. To verify whether a variable holds a NodeList or not, we can make use of the instanceof
operator.
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. Thediv
element with a class ofcontainer
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 thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <div class="change">1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> </div> <script src="script.js"></script> </body> </html>
.container{ border: 1px solid black; width: 200px; } .container div { border: 1px solid black; background-color: green; color: #fff; text-align: center; padding: 20px; }
Javascript
- We are using the
querySelector()
method to selectdiv
element with a class ofchange
and also we are using thequerySelectorAll()
method to select alldiv
elements except thediv
element with a class ofcontainer
. - You can see we are using the logical OR (
||
) operator here. This simply means ifquerySelector()
method returnsnull
, then executequerySelectorAll()
method. We are storing the returned value in theelement
variable. - We are using the
if
statement andinstanceof
operator to verify whether theelement
variable holds a NodeList or not. Depending upon the result, we will change the background color of either the firstdiv
element or the thirddiv
element to red.
const element = document.querySelector('.change') || document.querySelectorAll('.container div'); if(element instanceof NodeList){ element[3].style.backgroundColor = "red"; }else { element.style.backgroundColor = "red"; }