Reputation: 1892
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.
Upvotes: 5
Views: 11216
Reputation: 84
For new people who are searching for this use below code.
function findparentClass(node, clsName) {
if (node && !node.className) {
return findparentClass(node.parentNode, clsName);
} else if(node && node.className){
if(!node.classList.contains(clsName)){
return findparentClass(node.parentNode, clsName);
}else {
return true;
}
}
}
Simply send in the e.target element and the className you are looking for. If there present any parent with the className then the function will return true, othertimes it will retun undefined.
So, use it like,
document.addEventListener("click", function(e){
console.log(findparentClass(e.target, 'targetClassName'));
})
Upvotes: 0
Reputation: 1892
now i got the answer
document.onclick=function(e){
if (!e) e = window.event;
curDD = findparentClass(e.target.parentNode,'drop');
console.log(curDD);
}
}
function findparentClass(node, clsName) {
if(node.className != clsName && node.className!=null){
return findparentClass(node.parentNode,clsName);
}else if(node.className!=null){
return true;
}
}
where 'drop' is a class which you want to search...
Upvotes: 0
Reputation: 17381
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
Upvotes: 10
Reputation: 46647
the e
passed to an event handler is the event object, not the element that was clicked. Try grabbing the srcElement
, then it's parent's className
. Also, since you can't use jQuery, passing selectors like .drop
around won't do anything but cause syntax errors.
document.onclick = function(e){
console.log(e.srcElement.parentNode.className);
e.stopPropagation(); // don't bubble
};
Upvotes: 0