Search code examples
jqueryhtmldom-traversal

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?


Solution

  • $( '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/