This is my code:
<div id="main">
<div class="myclass"></div>
</div>
How can I detect if inside of main
div there is an element with myclass
set?
PS. Vanilla JS, no jQuery
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>
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>
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With