简体   繁体   中英

jQuery getting closest sibling element from $(this) not working

I want to hide the span closest to the button clicked and also hide the button.

The html goes like this

<!-- the div will be looped using php -->
<!-- this will only be a general idea of the code as the actual is very long and messy -->
<div>       
  <form><!-- This is like the head section -->
    <div>
        <div> <!-- some divs -->
            <button class="btn"></button> <!-- where i want it to work -->
                <div></div><!-- make this 5 times -->
            <span>content to hide</span>
        </div>
    </div>
  </form>      
  <div><!-- Comments to the head are here -->
    <button class="btn"></button><!-- button where it works -->
    <span>contains the comments</span>
  </div>
</div>

Script

$('.btn').click(function(){
    $(this).hide();
    $(this).next("span").hide();
});

I've tried the following below:

1. $(this).next("span").hide(); 
2. $(this).closest("span").hide();

It only works if I call all the span elements.

EDIT: the span is quite far as there are other elements like 5-10 elements before we reach the span.

This is what you need: JSFiddle

$(this).nextAll("span").first().hide();

nextAll() will look at all the next siblings (rather than just the first next one), and then we only want the first span that is found... first() achieves that

also, closest() will not work as it is looking up the tree, not at siblings.

EDIT 2: this answer selects the first siblings span, not the first sibling span after the button. The answer above using $(this).nextAll('span').first().hide() is the best answer.

$('.btn').click(function(){
    $(this).hide();
    $(this).siblings("span").first().hide();
});

closest() looks up the DOM tree, find() looks down, and siblings() is what you're looking for.

Edit 1: added first() after siblings() to only select the first one

you can try this way:

$('.btn').click(function(){
    var _that=$(this)
    _that.hide();
    _that.parent().find('*').eq(_that.index()+2).hide();
});

https://jsfiddle.net/3z5oyc4n/

+2 is for each element after your .btn (+1 = div, +2 = span)

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