slandau
slandau

Reputation: 24082

Get Id from parent

<div rownumber="0" messageid="112" class="post" style="position: relative; top: 0px;">
    <div class="post_body">hey hey hey</div>
    <div class="post_info" style="top: 0px;">
        <ul>
            <li class="vote"><a href="#">vote up</a></li>
            <li class="flag"><a href="#">flag</a></li>
        </ul>
    </div>
</div>

When I click on the 'vote up' or 'flag' href links, I want to be able to grab the messageId from the main containing div element. How would I do that?

Upvotes: 4

Views: 241

Answers (6)

JAAulde
JAAulde

Reputation: 19560

$( 'li.vote a, li.flag a' ).click( function( e )
{
    var msgId = $( this ).closest( 'div.post' ).attr( 'messageid' );

    e.preventDefault();
} );

Demo: http://jsfiddle.net/JAAulde/jQuGP/4/

Using a data- attribute and the jQuery .data() method would be best, though, as it would comply more closely with HTML standards: http://jsfiddle.net/JAAulde/jQuGP/5/

Upvotes: 4

kapa
kapa

Reputation: 78741

You can use .closest() to go up in the tree until a match is found. It is better suited here than .parents() which will filter all the parents of the link (which can be a lot of elements in a bigger markup), while .closest() stops when a match is found.

$('li.vote a, li.flag a').click(function () {
    var id=$(this).closest('div.post').attr('messageid');
});

Another important thing:

For storing arbitrary data on HTML elements, you should use the data- attributes (which were introduced in the HTML5 standard).

So in your example the HTML would be:

<div data-rownumber="0" data-messageid="112" class="post"...

Another advantage (besides a valid HTML document) is that you can simply get these data with the jQuery .data() function:

var id=$(this).closest('div.post').data('messageid');

jsFiddle Demo with data- attributes

Upvotes: 3

mightyplow
mightyplow

Reputation: 519

$( 'li.vote, li.flag' ).click(function() {
    var msgId = $(this).closest('[messageId]').attr('messageId');
)}

Upvotes: 0

fearofawhackplanet
fearofawhackplanet

Reputation: 53446

Use closest

$('.post a').click( function() {
    var msgId = $(this).closest('.post').attr('messageid');
});

Also, you should use the data- prefix on custom attributes to ensure conformity with web standards.

Upvotes: 3

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

This is untested, but something like this may work:

$(".vote a").click(function() {
    var value = $(this).parents(".post").attr("messageid");

    alert(value);
});

Upvotes: 1

Pwnna
Pwnna

Reputation: 9538

Can you get around the problem by dynamically output an id on the <a> element that contains the message id?

something like

<a href="#" id="message-123">

Upvotes: 0

Related Questions