twyntee_trey
twyntee_trey

Reputation: 185

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

Upvotes: 0

Views: 44

Answers (2)

SVSchmidt
SVSchmidt

Reputation: 6517

$(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

Upvotes: 0

j08691
j08691

Reputation: 207861

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

Upvotes: 1

Related Questions