0

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.

2
  • As in immediate children? Commented Jun 30, 2017 at 1:33
  • yes, an immediate child. Commented Jun 30, 2017 at 1:33

1 Answer 1

7

Sounds like you could use document.querySelector for this.

var exists = !!document.querySelector(".react-tab:not(.hidden) > #drawingDiv"); 
Sign up to request clarification or add additional context in comments.

4 Comments

Almost, it works, but when the class changes to .react-tab hidden it still "exists"
oh maybe try var exists = !!document.querySelector(".react-tab:not(.hidden) > #drawingDiv");
AWESOME!. You're the man. The next guy may have a nice googleable answer. I need to look into the querySelector logic.
@erikvold—you should add that comment to the answer, as it's actually the answer. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.