hey hey hey
<...">

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?

+4
source share
6 answers
 $( '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/

+4
source

Use closest

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

In addition, you must use the data- prefix for user attributes to ensure compliance with web standards.

+3
source

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'); 

jsFiddle Demo with data- attributes

+3
source

This has not been tested, but something like this might work:

 $(".vote a").click(function() { var value = $(this).parents(".post").attr("messageid"); alert(value); }); 
+1
source

Can you solve the problem by dynamically displaying an identifier in the <a> element that contains the message identifier?

sort of

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

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

All Articles