如何仅使用JavaScript检查父元素是否包含特定CSS类?

5

当我点击任何DOM元素时,我想检查它的父元素是否包含特定的类。我尝试了这种方式,但没能实现这个目标。有人知道该如何做吗?

document.onclick=function(e){
    console.log(e.parentElement('.drop').id);       
}

请只使用JavaScript提供解决方案,我不能使用jQuery。

该类可以在“className”属性中找到。 - Pointy
你是在检查直接父级还是所有父级? - Rory McCrossan
如果您想要检查所有的祖先,请访问:https://dev59.com/4WQn5IYBdhLWcg3wZGZ4 - djvg
4个回答

10
您可以使用父元素的classList属性,它具有一个contains()方法,对您的目的非常有用:
document.onclick=function(e){
    console.log( e.parentElement.classList.contains( 'drop' ) );       
}

如果你的目标是Internet Explorer (IE<10),你可以手动解析类列表并查找其中的“drop”:

document.onclick=function(e){
    console.log( e.parentElement.className.split(' ').indexOf('button-panel')!==-1 );
}

split()函数将className参数解析为多个名称,并返回一个数组。

indexOf()函数用于在数组中搜索元素,如果找不到,则返回-1。


classList 仅在 IE 版本 10 及以上版本中受支持。https://developer.mozilla.org/zh-CN/docs/DOM/element.classList#Browser_compatibility - sv_in
感谢您的评论。我添加了新版本的代码来消除这个问题。 - AlexStack
我非常确定 console.parentElement 将是未定义的。 - jbabey
我认为这是正确的答案。document.onclick=function(e){ console.log(e.target.parentElement.classList.contains( 'drop' );
}
- coder
@jbabey:感谢指出。那是个打字错误。已经修复了。 - AlexStack

0

传递给事件处理程序的e是事件对象,而不是被单击的元素。尝试获取srcElement,然后是其父级的className。此外,由于您无法使用jQuery,因此传递像.drop这样的选择器将什么也不做,只会导致语法错误。

document.onclick = function(e){
    console.log(e.srcElement.parentNode.className);

    e.stopPropagation(); // don't bubble
};

工作示例


请在给出反对票时留下评论,以便回答可以得到改进。 - jbabey

0
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;    
    }
}

其中 'drop' 是您想要搜索的类...


0
对于新来的人,如果你正在寻找这个,请使用以下代码。

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;
        }
    }
}

只需将e.target元素和要查找的className发送进去。如果存在具有该className的父级,则函数将返回true,否则将返回undefined。
因此,使用方法如下:

document.addEventListener("click", function(e){
  console.log(findparentClass(e.target, 'targetClassName'));

})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接