How To Get The Nth Child Of An Element Using JavaScript

Get the nth child of an Element using JavaScript

When working with JavaScript, you may need to get the Nth child of an element. For example, you could add an active class to the third list item in the navigation menu. Alternatively, you could style the second paragraph within a div block. Fortunately, there are some different ways to do this. This article will look at how to get the nth child of an element using JavaScript.

Get the nth child of an element using JavaScript

Here are the three simplest ways. Let’s read together and decide which way is best!

Using document.querySelector()

The querySelector() method returns the first element that matches a specified CSS selector.

To get the nth child of an element, use querySelector() in conjunction with the nth-child selector. For example, suppose you want to get the second child element of a parent element. Use the code below:

document.querySelector("parent:nth-child(2)")

See the example below to understand better!

<body>
  <main id="app">
    <div class="header">
      <h1 id="heading-primary">Hello, This is LearnShareIT</h1>
      <nav class="menu">
        <ul class="menu-list">
          <li>JavaScript</li>
          <li>Python</li>
          <li>Java</li>
          <li>C#</li>
        </ul>
      </nav>
    </div>
  </main>
  <script defer src="script.js"></script>
</body>
// Use querySelector() and CSS selector to get the 2nd li
const secondLi = document.querySelector(".menu-list :nth-child(2)");

// Change background color for 2nd li
secondLi.style.backgroundColor = "#b9c05d";

Output:

If you want to get multiple child elements, use the querySelectorAll() method. This method returns all elements that match the CSS selector you passed in. Like this:

// Use querySelectorAll() and CSS selector to get the odd li items
const oddLi = document.querySelectorAll(".menu-list>:nth-child(odd)");

// Change background color for odd li items
for (let li of oddLi) {
  li.style.backgroundColor = "#b9c05d";
}

Output:

Using childNodes property

The childNodes property returns a NodeList of a node’s child. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

To return the specified node’s children, use the following syntax:

parent.childNodes[i];

This syntax will return the parent’s specified child node. Now, let’s apply this syntax to our example.

// Get the parent element
const ul = document.querySelector(".menu-list");

// Log the childNodes to locate the second li
console.log(ul.childNodes);

// Change background color for second li
const secondLi = (ul.childNodes[3].style.backgroundColor = "#b9c05d");

Output:

NodeList(9) [text, li, text, li, text, li, text, li, text]

Using NodeList.item() and children property

The item() method returns a node from a node list, as specified by an index number.

The children property of an element returns all child elements of that element.

To get the nth child of an element, first, use the children property on the parent element to get a list of child elements. Then, pass an index to the item() method to specify the child element. Like this:

// Get the list of child elements
const listOfli = document.querySelector(".menu-list").children;

// Use item() to get the 3rd li
const thirdLi = listOfli.item(2);

// Change background color for 3rd li
thirdLi.style.backgroundColor = "#b9c05d";

Output:

Summary

In summary, we hope you enjoyed this article. The querySelector() method and childNodes property are great approaches to get the nth child of an element using JavaScript. As always, if you have any questions or comments, please feel free to leave us a message below.

Happy coding!

Maybe you are interested:

Leave a Reply

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