Get Child Element by ID using JavaScript


Borislav Hadzhiev

Mon Dec 27 20212 min read

Get Child Element by ID using JavaScript #

To get a child element by class:

  1. Use the document.querySelector() method to get the parent element.
  2. Call the querySelector method on the parent element passing it the id as a parameter.
  3. For example, parent.querySelector('#first') gets the child with id first.

Here is the HTML for the examples in the article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <div id="first">Child 1</div> <div>Child 2</div> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const parent = document.querySelector('#parent'); console.log(parent); // 👉️ div#parent const child = parent.querySelector('#first'); console.log(child); // div#first

We used the document.querySelector method to get the parent element by its id.

In this scenario, you could have used the document.getElementById method to achieve the same result, e.g.:

const parent = document.getElementById('parent');
Notice that when using the querySelector method we prefix the id with a hash # and when using getElementById - we don't.

The next step is to call the querySelector method on the parent element.

When the querySelector method is scoped to a specific element, it only selects the children of the element the method was called on.

The Element.querySelector method returns the first element that matches the provided selector.

In the example, we select a child element that has an id value set to first.

Note that with the approach of passing the class name to the querySelector method, we are selecting any of the children of the element.

This includes nested children that have the supplied id.

However, in this scenario, it shouldn't matter because the id values on your page should be unique.

Having multiple elements with the same id on a single page can lead to confusing behavior and difficult to track bugs.

Use the search field on my Home Page to filter through my more than 1,000 articles.