Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check parents elements contain a specific CSS class by only using javascript?

Tags:

javascript

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.

like image 579
coder Avatar asked Jan 14 '23 11:01

coder


1 Answers

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

like image 65
AlexStack Avatar answered May 21 '23 00:05

AlexStack