简体   繁体   中英

jQuery select previous element with a class

I have the following:

<div class="input-group-btn">
     <button type="button" class="btn btn-default dropdown-toggle ranking-toggle" data-toggle="dropdown"><span class="chosen-rank">Ranking</span> <span class="caret"></span></button>
    <ul class="dropdown-menu ranking-dropdown pull-right">
         <li><a href="javascript:void(0)">#1</a></li>
         <li><a href="javascript:void(0)">#2</a></li>
         <li><a href="javascript:void(0)">#3</a></li>
    </ul>

And when I click on any of the anchors in the dropdown I want to replace the 'Ranking' text in chosen-rank span to the chosen #.

I figured the following might work but it's not targeting the span.chosen-rank:

$('.ranking-dropdown li a').click(function() { 
   $(this).closest('span.chosen-rank').text(this.text);
});

Maybe need to use some combination of prev() and/or parent() methods, not sure nothing so far seems to work. The reason I don't just target the span directly is because I have multiple dropdowns like this on the page

You need to go up a bit farther in the DOM (with .closest() ), then back down (with .find() ):

$('.ranking-dropdown li a').click(function () {
    $(this).closest('.input-group-btn').find('span.chosen-rank').text(this.text);
});

jsFiddle example

$(this).parents(".input-group-btn").find(".chosen-rank").text(this.text);

should work: http://api.jquery.com/parents/ & http://api.jquery.com/find/

EDIT: See my Fiddle

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