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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With