Borislav Hadzhiev
Mon Dec 27 2021·2 min read
Photo by Noah Silliman
To get a child element by class:
document.querySelector()
method to get the parent element.querySelector
method on the parent element passing it the class
name as a parameter.parent.querySelector('.first')
gets the child with class
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 class="first">Child 1</div> <div class="second">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 child1 = parent.querySelector('.first'); console.log(child1); // div.first const children = parent.querySelectorAll('.first'); console.log(children); // 👉️ [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');
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 child element that matches
the provided selector.
If you need a collection of the children that have the specific class, use the Element.querySelectorAll method instead.
querySelector
andquerySelectorAll
method we are selecting any of the children of the element.This includes nested children that have the supplied class.
If you only want to target direct children of the DOM element, use the :scope
pseudo-class selector.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <div class="first"> Child 1 <!-- 👇️ Nested element with same class --> <div class="first">Nested Child 1</div> </div> <div class="second"> 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 child1 = parent.querySelector(':scope > .first'); console.log(child1); // div.first const children = parent.querySelectorAll(':scope > .first'); console.log(children); // 👉️ [div.first]
We used the :scope
pseudo-class to select the
direct children
of the DOM element that have a class of first
.
When used with methods like querySelector
and querySelectorAll
, :scope
matches the element on which the method was called (the parent).