Search code examples
javascriptjqueryparentsiblings

Get the ID of a sibling after a link is clicked


I use the following code and I would like to be able to get the ID attribute from the <li> (the post ID) that is associated with an <a> when it is clicked, but I cannot figure out how do do this. Is anybody able to help me at all?

<li id="custom_latest_news-5" class="widget custom_widget_latest_news">
    <div class="widget-title">
        <a href="http://test.dynedrewett.com/news-and-events/">Latest news</a>
    </div>
    <div class="widget-content">
        <ul class="link-list ajax-links">
            <li id="post-5521"><a href="http://mydomain.com/uk-news/last-call-for-self-assessment-tax-forms/">Last call for self-assessment tax forms</a></li>
            <li id="post-5523"><a href="http://mydomain.com/uk-news/young-drivers-gambling-on-no-insurance/">Young drivers gambling on no insurance</a></li>
            <li id="post-5520"><a href="http://mydomain.com/uk-news/tenants-forced-to-abandon-pets/">Tenants forced to abandon pets</a></li>
        </ul>
    </div>
</li>

Here is the JS that I currently have -

/**
 * Intercept a click for page refresh and run the page refresh JS
 */
$(function(){
    $('.ajax-links').delegate('li a', 'click', function(e){
        /** Prevent the click from doing anything */
        e.preventDefault();

        /** Get the post ID */  
        var post_id = '???';
    });
});

Thanks.


Solution

  • I believe you need

    var post_id = $(this).parent().attr('id');

    Example: http://jsfiddle.net/FwqGT/