检查父元素是否仅使用javascript包含特定的CSS类?
当我单击任何DOM元素时,我想检查它的父元素是否包含特定的类。我正在用这种方式尝试,但无法实现这个目标。有人知道怎么做吗检查父元素是否仅使用javascript包含特定的CSS类?,javascript,Javascript,当我单击任何DOM元素时,我想检查它的父元素是否包含特定的类。我正在用这种方式尝试,但无法实现这个目标。有人知道怎么做吗 document.onclick=function(e){ console.log(e.parentElement('.drop').id); } 请仅用JavaScript给出解决方案-我不能使用jQuery。传递给事件处理程序的e是事件对象,而不是单击的元素。尝试抓取src元素,然后它是父级的类名。此外,由于不能使用jQuery,因此传递诸如.dr
document.onclick=function(e){
console.log(e.parentElement('.drop').id);
}
请仅用JavaScript给出解决方案-我不能使用jQuery。传递给事件处理程序的
e
是事件对象,而不是单击的元素。尝试抓取src元素
,然后它是父级的类名
。此外,由于不能使用jQuery,因此传递诸如.drop
之类的选择器除了会导致语法错误外,什么也做不了
document.onclick = function(e){
console.log(e.srcElement.parentNode.className);
e.stopPropagation(); // don't bubble
};
您可以使用父元素的
classList
属性。它有一个contains()
方法,可用于您的目的:
document.onclick=function(e){
console.log( e.parentElement.classList.contains( 'drop' ) );
}
如果您的目标是Internet Explorer(即
其中“drop”是要搜索的类…该类位于“className”中属性。您是在检查直接父级还是所有父级?
classList
仅在版本10的IE中受支持。感谢您的评论。我添加了新版本的代码以消除此问题。我非常确定console.parentElement
将被取消定义。我认为这是正确的答案。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。document.onclick=function(e){console.log(e.target.parentElement.classList.contains('drop');}@jbabey:感谢您指出这一点。这是一个拼写错误。修复了它。请在否决投票时发表评论,以便改进答案。
document.onclick=function(e){
console.log( e.parentElement.className.split(' ').indexOf('button-panel')!==-1 );
}
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;
}
}