May 11, 2011

jQuery select parent

Question by cabaret

This might be a duplicate question, however I did search and I got so many different answers that I don’t know which to use or how to do this.

<?
if(isset($content))
{
    $i = 1;
    foreach($content as $item)
    {
        echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>";
        $i++;
    }
}
?>

I’ve added a function to these links with jQuery to handle an ajax call. I select the links as follows:

    $("#tips_list ul li a").click(function(e)   { //... }

However, this doesn’t make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I’d re-structure my HTML so the anchor tag wraps around the li tag.

    `<a href="#" name=""><li>foo</li></a>`

I then changed my jQuery code accordingly:

    $("#tips_list ul a li").click(function(e)   { //... }

However, now, when I click.. it grabs the list item tag as $(this); which means I can’t really grab the name attribute from the anchor tag. So! What I need to do is to grab the name attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I’m not that experienced with jQuery.

Thanks a lot for helping me!

Answer by phil

How about going back to the original method, and set #tips_list ul li a {display:block} in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.

Answer by Starx

Keep the old markup. The later one is quite cranky and use the following script.

$("#tips_list ul li").click(function(e)   {
    var name = $(this).children("a").attr("name");
    alert(name);
}
...

Please fill the form - I will response as fast as I can!