Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Check if class exists somewhere in parent - vanilla JS

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>
question from:https://stackoverflow.com/questions/16863917/check-if-class-exists-somewhere-in-parent-vanilla-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...