Introduction to DOM selectors (Part 2) (NodeList and HTML collection)

Introduction to DOM selectors (Part 2) (NodeList and HTML collection)

Understanding how to select and manipulate DOM elements is crucial in web development. Let's explore some powerful methods: querySelector, querySelectorAll, and getElementsByClassName.

Using querySelector

The querySelector method allows you to select the first element that matches a specified CSS selector.

document.querySelector("h1");
// Outputs: <h1 id="title" class="heading" style="background-color: green;">DOM Learning</h1>

This selects the first <h1> element in the document.

Example

Consider the following HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM learning</title>
</head>
<body class="bg_black">
    <div>
        <h1 id="title" class="heading">DOM learning on chai aur code</h1>
        <p>Lorem ipsum dolor sit amet.</p>
        <input type="password">
        <ul>
            <li class="list-item">one</li>
            <li class="list-item">two</li>
            <li class="list-item">three</li>
            <li class="list-item">four</li>
        </ul>
    </div>

<div>
    <h1>DOM Learning</h1>
    <h2 class="javascript">Hello JS</h2>
    <h2 class="python">Hello Python</h2>
</div>

</body>
</html>

To select the first <h2> element:

document.querySelector("h2");
// Outputs: <h2 class="javascript">Hello JS</h2>

You can also use IDs and classes:

document.querySelector("#title");
// Outputs: <h1 id="title" class="header">DOM Learning</h1>

document.querySelector(".heading");
// Outputs: <h1 id="title" class="header">DOM Learning</h1>

Selecting Input Fields

For input fields, you can be even more specific:

document.querySelector('input[type="password"]');
// Outputs: <input type="password">

Selecting List Items

To select list items:

<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

Select the first list item using CSS selectors:

document.querySelector("ul > li");
// Outputs: <li>one</li>

//another way
const myUl = document.querySelector("ul");
myUl.querySelector("li");
// Outputs: <li>one</li>

Changing Styles and Text Content

To manipulate styles and text content: now we want to turn the first li green with a padding of 10px:

const turnGreen = myUl.querySelector("li");
turnGreen.style.color = "green"
turnGreen.style.padding = "10px"

// Alternatively, in a single line:
document.querySelector("ul > li").style.color = "green";

// Changing the text content:
turnGreen.innerText = "five";

Using querySelectorAll

The querySelectorAll method returns all elements that match the CSS selector, as a NodeList.

document.querySelectorAll("li");
// Outputs: NodeList(3) [li, li, li]

A NodeList is an array-like collection (list) of Node Objects. The nodes in a NodeList can be accessed by index (starts at 0). The length property returns the number of nodes in a NodeList.

So does this means, NodeList is an array?

NodeList and HTML collections are not pure array

Accessing NodeList Items

now if we have selected all the li items and want to change the color of first li item

const tempLiList = document.querySelectorAll("li");

tempLiList.style.color = "red";
//it will throw an error saying "can't set properties of undefined"

tempLiList[0].style.color = "red";
// Sets the color of the first <li> to red
//as we have selected all the li, therefore we have to tell which one we have to select

Even for a single element which is unique in the whole document:

const myH1 = document.querySelectorAll("h1");

myH1.style.color = "green"; //this will throw the same error

myH1[0].style.color = "green";
// Sets the color of the <h1> to green

Using getElementsByClassName

The getElementsByClassName method returns a live HTMLCollection of all elements with the specified class name. An HTMLCollection is an array-like collection (list) of HTML elements. The length Property returns the number of elements in the collection.

Example

Consider the following HTML structure:

<ul>
    <li class="list-item">one</li>
    <li class="list-item">two</li>
    <li class="list-item">three</li>
    <li class="list-item">four</li>
</ul>

Select elements by class name:

const tempList = document.getElementsByClassName("list-item");
// Outputs: HTMLCollection(4) [li.list-item, li.list-item, li.list-item, li.list-item]

now in the prototype of the HTML collection, we don't have any method to loop on this HTML collection, therefore we will convert it into an array:

const myConvertedArray = Array.from(tempList);
//output:
//(4) [li.list-item, li.list-item, li.list-item, li.list-item]
//0: li.list-item
//1: li.list-item
//2: li.list-item
//3: li.list-item
length: 4
[[prototype]]: Array

now we can easily apply forEach/map or different methods/functions available like:

const myConvertedArray = Array.from(tempList);
myConvertedArray.forEach(function (li) {
    li.style.color = "orange";
});