17

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!

1 Answer 1

36

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.

Sign up to request clarification or add additional context in comments.

11 Comments

So "child2" is added dynamically on load if data was received from the server. If not, it's not added. When I do something inside the website, I want it to add to "child2" and create another "child2." Even if it does exist aftering loading the data, it keeps telling me it doesn't exist
@KodyR. When you look in the DOM inspector from your browser's developer console, you can see the element but the above code does not work? I think that would be extremely strange. How sure are you that parentDiv refers to the correct node?
I just looked and it isn't there in the code but it's definitely on my screen. Very strange
How do you check the code? ... With "view source" or developer tools (Chrome) or ..?
@KodyR. when you click "Inspect Element" on your red box, it should highlight the clicked element in the view of the DOM.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.