Check if element has child node element by id name

Sorry if this is a simple question! I am new to javascript.

I am trying to check if a div has a specific child (I will call it "child2"). I know about .hasChildNodes (), but as far as I know, this only lets you know if there are child nodes. I tried .contains like this:

if (parentDiv.contains(child2) == false) { 

but even if parentDiv contains child2, it still returns false. It seems like such a simple thing, and I'm trying to search around, but I had no luck in pure js. Thanks!

+5
source share
2 answers

You can use querySelector() :

 var hasChild = parentDiv.querySelector("#child2") != null; 

The querySelector() method allows you to search for a subtree below the source element using the specified CSS selector string. If an element is found, its DOM node is returned.

+8
source

You need to make this if work.

 var parentDiv = document.getElementById("parentDiv"); var childDiv = document.getElementById("childDiv"); if (parentDiv.contains(childDiv)) { alert("yes"); } 
 <div id="parentDiv"> <div id="childDiv"> </div> </div> 
+1
source

Source: https://habr.com/ru/post/1244766/


All Articles