检查父类中的某个类是否存在 - vanilla JS [英] Check if class exists somewhere in parent - vanilla JS

查看:122
本文介绍了检查父类中的某个类是否存在 - vanilla JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很努力地看到如何做到这一点。我想检查一个类是否存在于元素的一个父元素中的某个位置。



我不想使用任何库,只是使用vanilla JS。 p>

在下面的示例中,如果有问题的元素驻留在具有-class的元素的子元素的某个位置作为类名称,那么它应该返回true。



我认为这样就可以用jQuery:

  if($(' #the-element')。parents()。hasClass('the-class')){
return true;
}

所以这返回true:

 < div> 
< div class =the-class>
< div id =the-element>< / div>
< / div>
< / div>

这样做:

 < div class =the-class> 
< div>
< div id =the-element>< / div>
< / div>
< / div>

...但这会返回false:

 < DIV> 
< div class =the-class>
< / div>
< div id =the-element>< / div>
< / div>


解决方案

您必须递归执行: p>

  //如果元素或其父类之一具有类classname 
函数,则返回true hasSomeParentTheClass(element,classname){
if(element.className.split('').indexOf(classname)> = 0)return true;
return element.parentNode&&& hasSomeParentTheClass(element.parentNode,classname);
}

演示(打开控制台以查看 true


I'm really struggling to see how to do this. I want to check if a class exsits somewhere in one of the parent elements of an element.

I don't want to use any library, just vanilla JS.

In the examples below it should return true if the element in question resides somewhere in the childs of an element with "the-class" as the class name.

I think it would be something like this with jQuery:

if( $('#the-element').parents().hasClass('the-class') ) {
    return true;
}

So this returns true:

<div>
    <div class="the-class">
        <div id="the-element"></div>
    </div>
</div>

So does this:

<div class="the-class">
    <div>
        <div id="the-element"></div>
    </div>
</div>

...but this returns false:

<div>
    <div class="the-class">
    </div>
    <div id="the-element"></div>
</div>

解决方案

You'll have to do it recursively :

// returns true if the element or one of its parents has the class classname
function hasSomeParentTheClass(element, classname) {
    if (element.className.split(' ').indexOf(classname)>=0) return true;
    return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
}

Demonstration (open the console to see true)

这篇关于检查父类中的某个类是否存在 - vanilla JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆