Brian Stallter
Brian Stallter

Reputation: 159

Find if child element of parent element exists

I've searched for a while now, and thought if for nothing else, to document this case here for future users.

How do I find out if a certain element contains a certain child element in the DOM using plain javascript? I have in my app an element with class 'react-tab'. It will become hidden, and no longer 'react-tab' but 'react-tab hidden' when the tab is in the background.

I want to check if the active class 'react-tab' div contains a div with id="drawingDiv".

so something like:

if(document.getElementsByClass("react-tab").contains("drawingDiv"))

or

if(document.getElementsByClass("react-tab").childNodes.contains("drawingDiv"))

I have yet to get the right answer, I do not want to use jQuery.

Upvotes: 0

Views: 1447

Answers (1)

erikvold
erikvold

Reputation: 16558

Sounds like you could use document.querySelector for this.

var exists = !!document.querySelector(".react-tab:not(.hidden) > #drawingDiv");

Upvotes: 7

Related Questions