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 the "voice up" or " href " flag links, I want to be able to grab the messageId from the main containing the div element. How can I do it?
$( '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 the data- attribute and the jQuery .data() method would be best since it would conform to higher HTML standards: http://jsfiddle.net/JAAulde/jQuGP/5/
You can use .closest() to go up the tree until a match is found. Here it is better suited than .parents() , which will filter all the parents of the link (which may be more elements in more markup), and .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:
To store arbitrary data in HTML elements, use the data- attributes (which were introduced in the HTML5 standard).
So in your HTML example:
<div data-rownumber="0" data-messageid="112" class="post"... Another advantage (besides a valid HTML document) is that you can simply get this data using the jQuery .data() function :
var id=$(this).closest('div.post').data('messageid');