chris
chris

Reputation: 36957

jquery select parent elements sibling

Ok, lets see if I can explain this clearly enough here. My HTML looks like

<li>
    <div class="info_left" rel="snack">Fries</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>
<li>
    <div class="info_left" rel="lunch">Burger</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>
<li>
    <div class="info_left" rel="4thmeal">Taco</div>
    <div class="info_right">
        <span class="info_remove">[Remove]</span>
        <span class="info_favorite">[Favorite]</span>
    </div>
</li>

If you will note you will see a "Remove" and "Favorite" inside a div "info_right". What I need to do when either one of those 2 options is clicked on is get the rel and text values of the same li's "info_left" div. I've tried a few ways but don't think I'm nailing the combo between parent(s), siblings correctly or I dunno. Either way hoping someone can toss me a bone.

Upvotes: 0

Views: 785

Answers (3)

dku.rajkumar
dku.rajkumar

Reputation: 18588

try this

$('.info_remove,.info_favorite').click(function() {
   var target_elem = $(this).parent().prev();
   alert(target_elem.attr('rel'));
   alert(target_elem.text());
});

fiddle : http://jsfiddle.net/ss37P/1/

Upvotes: 0

TOUDIdel
TOUDIdel

Reputation: 1302

jsFiddle example

$(document).ready(function(){
    $(".info_right span").click(function(){
        $("#msg").html($(this).attr("class")+": "+$(this).parent().prev().attr("rel"));
    })
})

Upvotes: 0

Alnitak
Alnitak

Reputation: 339985

It should just be:

$('.info_remove,.info_favorite').on('click', function() {
   var $left = $(this).parent().siblings('.info_left');
   var rel = $left.attr('rel');
   var txt = $left.text();
   ...
});

Upvotes: 1

Related Questions