jQuery add class to nearest element which exists multiple times

I have a structure like this:

<span class="side">
    <ul>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><span class="copy-short-url"><i class="fas fa-link"></i></span></li>
        <span class="confirm">Copied!</span>
    </ul>
</span>

...

<span class="side">
    <ul>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><span class="copy-short-url"><i class="fas fa-link"></i></span></li>
        <span class="confirm">Copied!</span>
    </ul>
</span>

...

<span class="side">
    <ul>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><span class="copy-short-url"><i class="fas fa-link"></i></span></li>
        <span class="confirm">Copied!</span>
    </ul>
</span>

...

<span class="side">
    <ul>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><a href="#"><i class="fas fa-print"></i></a></li>
        <li><span class="copy-short-url"><i class="fas fa-link"></i></span></li>
        <span class="confirm">Copied!</span>
    </ul>
</span>

I now want to add a class to the span "confirm". But only for the span that belongs to the corresponding code block. So when I click on the second span "copy-short-url" only the second span "confirm" must get the additional class.

How can I do this? Thanks!

1 answer

  • answered 2018-03-13 20:25 Taplar

    Provided you are in the click event handler for .copy-short-url

    $(this).closest('.side').find('.confirm').addClass('whatever');
    

    closest() goes up the dom tree through parents until it finds a match.
    find() goes down through children finding all matches.

    Edit: In regard to your timeout question in the comments.

    var $confirm = $(this).closest('.side').find('.confirm');
    $confirm.addClass('whatever');
    setTimeout(function(){ $confirm.removeClass('whatever'); }, 2000);