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. 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 have also included our javascript file script.js with a script 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 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.
const element = document.querySelector('.change') || document.querySelectorAll('.container div');

if(element instanceof NodeList){
    element[3].style.backgroundColor = "red";
}else {
    element.style.backgroundColor = "red";
}