Kody R.
Kody R.

Reputation: 2460

Check if element has child node by id name

I apologize if this is an easy question! I'm pretty new to javascript.

I'm trying to check if a div has a specific child element (I'll name it 'child2'). I know about .hasChildNodes() but as far as I know it only lets you know if child nodes exist. I tried .contains like so:

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

but even if the parentDiv does contain child2, it still returns false. It seems like such a simple thing to do and I've been trying to search around but I haven't had any luck in pure js. Thanks!

Upvotes: 16

Views: 32463

Answers (1)

Pointy
Pointy

Reputation: 413828

You can use querySelector():

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

The querySelector() method lets you search the subtree beneath the starting element using the given CSS selector string. If the element is found, its DOM node is returned.

Upvotes: 35

Related Questions