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.
querySelectormethod on the parent element passing it the id as a parameter.
parent.querySelector('#first')gets the child with id
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>
const parent = document.querySelector('#parent'); console.log(parent); // 👉️ div#parent const child = parent.querySelector('#first'); console.log(child); // div#first
We used the
method to get the parent element by its
In this scenario, you could have used the
document.getElementById method to
achieve the same result, e.g.:
const parent = document.getElementById('parent');
querySelectormethod 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.
querySelectormethod is scoped to a specific element, it only selects the children of the element the method was called on.
Element.querySelector method returns the first element that matches the
In the example, we select a child element that has an
id value set to
querySelectormethod, 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.
I'll send you 1 email a week with links to all of the articles I've written that week