chris
chris

Reputation: 36937

jQuery how can I find the li that a div is in?

I am trying

$(this).parent('li').attr('widgetid')

Because when I click within the following layout I want to find the widgetid

<li widgetid="1">
    <div class="widgetHeader">
        <div class="widgetIcon"></div>
        <div class="widgetTitle"></div>
        <div class="widgetEdit"></div>
        <div class="widgetClose"></div>
    </div>
    <div class="widgetHeader"></div>
</li>

but I am getting "undefined" so I think I lost myself "widgetClose" is the trigger div for what I am attempting to do.

Upvotes: 1

Views: 86

Answers (4)

Tryster
Tryster

Reputation: 199

Instead of using the parent method with a selector (which will only return a value if the immediate parent matches the selector), you could use the parents method:

$(this).parents("li:eq(0)").attr("widgetid")

The parents method will look at all ancestor elements and return all that match the selector (in this case the selector asks for the first li that if found).

Upvotes: 1

Rafay
Rafay

Reputation: 31033

you can use .parents along with event.stopPropagation

$("div").click(function(e){
    e.stopPropagation();
alert($(this).parents('li').attr('widgetid'));

});

http://jsfiddle.net/FhVgp/3/

Upvotes: 1

Jose Faeti
Jose Faeti

Reputation: 12302

You should bind only one click event listener for only the parent of all clickable elements anyway, then use event.target within the click function to refer to the clicked element.

From there, you can find the closest <li> element using jQuery .closest() method.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

You could use:

$(this).closest('li').attr('widgetid');

References:

Upvotes: 4

Related Questions