Check if Element has Child with specific ID using JS

avatar

Borislav Hadzhiev

Last updated: Jan 11, 2022

banner

Check out my new book

Check if Element has Child with specific ID using JS #

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box.querySelector('#child-3') !== null) {}. The querySelector method returns the first element that matches the provided selector or null of no element matches.

Here is the HTML for the examples in this article.

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

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (box.querySelector('#child-3') !== null) { console.log('✅ element has child with id of child-3'); } else { console.log('⛔️ element does NOT have child with id'); }

We used the getElementById method to select the parent element.

The querySelector method can be scoped to a specific element and returns the first element that is a descendant of the element the method was called on and matches the provided selector.

If no element matches the provided selector, the querySelector method returns null.

In our if statement, we check if the returned value is not equal to null. If the element is found, the if block is ran, otherwise the else block runs.

If you haven't selected the parent element yet, you can do this in a single step.

index.js
if (document.querySelector('#box #child-3') !== null) { console.log('✅ element has child with id of child-3'); } else { console.log('⛔️ element does NOT have child with id'); }
We used the querySelector method to select an element that has an id of child-3 that is a descendant of an element with an id of box.

The selector you pass to the querySelector method can be as specific as necessary. The following example only checks if any of the element's direct children have the id.

index.js
if (document.querySelector('#box > #child-3') !== null) { console.log('✅ element has child with id of child-3'); } else { console.log('⛔️ element does NOT have child with id'); }

The selector above would not match any of the nested children of the element with id of box that have an id of child-3.

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