简体   繁体   中英

jQuery closest (closest that hasClass when elements have multiple classes)

I can't understand how I will get the jQuery "closest" to work when elements have multiple classes.

The code below alerts "DIV" but I would like it to alert "SPAN" since "SPAN" is the first element (self or parent) that has the class "box".

So, how can I do this?

<div class="box">
    <span class="red box">
        <a class="elem" />
    </span>
</div>

$(document).ready(function () {
    var nodeName = $('.elem').closest('.box').prop('nodeName');
});

jquery: 1.11.2

The problem lies in how you have written your HTML.

If you close the <a> tag, everything works fine ( see fiddle ):

<div class="box">
    <span class="box">
        <a class="elem"></a>
    </span>
</div>

With your code, jQuery sees the <span> and <a> as siblings, because in HTML5 there are no "self-closing" elements, but just elements with no closing tag, like <br> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM