Borislav Hadzhiev
Mon Dec 27 2021·2 min read
Photo by Jordan Whitfield
To get a child element by class:
document.querySelector()
method to get the parent element.querySelector
method on the parent element passing it the id as a
parameter.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');
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.
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
.
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.