When I click on any DOM element I want to check if its parents element contains a specific class or not. I am trying in this way but can't achieve this goal. Does anyone know how?
document.onclick=function(e){
console.log(e.parentElement('.drop').id);
}
Please give solution in JavaScript only - I can't use jQuery.
You can use the classList
property of the parent element. It has a contains()
method that is useful for your purpose:
document.onclick=function(e){
console.log( e.parentElement.classList.contains( 'drop' ) );
}
If you are targeting Internet Explorer, (IE<10), you can manually parse the list of classes and look for 'drop' in them:
document.onclick=function(e){
console.log( e.parentElement.className.split(' ').indexOf('button-panel')!==-1 );
}
split()
parses the className to multiple names in an array.
indexOf()
searches for an element in an array, if it can't find it, it returns -1
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