10

This is my code:

<div id="main"> <div class="myclass"></div> </div> 

How can I detect if inside of maindiv there is an element with myclass set?

PS. Vanilla JS, no jQuery

3 Answers 3

12

The below code searches for any element with a class inside a parent using querySelectorAll():

if (document.querySelectorAll("#main .myclass").length > 0) { console.log("#main has .myclass inside"); } else { console.log("#main has no .myclass inside"); }
<div id="main"> <div class="myclass"></div> </div>

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

1 Comment

After seeing this, I have just now realized that getting element functions in javascript can occur on any node, and now I sort of more understand how the "document" is a node, but so are each elements. Sort of just had an epiphany on how javascript works.
1

You can use:

if(document.getElementById('main').getElementsByClassName('myclass')[0]) { alert('class found'); }else{ alert('class not found'); }
<div id="main"> <div class="myclass"></div> </div>

Comments

1

classList

There are multiple ways to achieve this. One very nice solution is to use the classList Method contains. https://developer.mozilla.org/de/docs/Web/API/Element/classList

querySelector

But I would prefer querySelector because you can easily check if the querySelector finds an element. (If it doesn't, then querySelector returns null)

function checkOne() { const check = document.querySelectorAll('#main > div'); const res = []; check.forEach(e => { if (e.classList.contains('myclass') ) { res.push(true); } }) return res.length > 0 ? true : false; } function checkTwo() { const check = document.querySelector('#main .myclass'); return check ? true : false; } console.log("checkOne", checkOne()); console.log("checkTwo", checkTwo());
<div id="main"> <div class="hello">1</div> <div class="myclass">1</div> <div class="world">1</div> </div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.