Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element has child node by id name

Tags:

javascript

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!

like image 446
Kody R. Avatar asked Mar 09 '16 20:03

Kody R.


1 Answers

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.

like image 131
Pointy Avatar answered Sep 25 '22 00:09

Pointy