Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript detect if child of parent element has a class set

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

like image 372
paulalexandru Avatar asked Dec 15 '16 14:12

paulalexandru


3 Answers

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>
like image 128
DontVoteMeDown Avatar answered Oct 30 '22 10:10

DontVoteMeDown


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>
like image 34
Ionut Avatar answered Oct 30 '22 09:10

Ionut


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>
like image 32
Maik Lowrey Avatar answered Oct 30 '22 10:10

Maik Lowrey