tags:

views:

38

answers:

2

Hi,

I have the following:

<ul id ='foo'>
    <li><p>hello</p></li>
    <li><p>hello</p></li>
    <li><p>hello</p></li>
</ul>

$('#foo').delegate('li', 'click', function(event) {
    var target = $(event.target);
    console.log(target);   
});

the click handler gets called whenever one of the inner p elements gets clicked, as well as the parent li elements.

How can I get a pointer to the parent li element, regardless of which inner child element was clicked? For example, my real li elements look like:

<li>
  <p>one</p>
  <div>
    <p>two</p>
  </div>
</li>

so I'm finding I have to have several checks to get back up to the parent li that was clicked. Is there a way to just select the parent of a type like:

$('#foo').delegate('li', 'click', function(event) {
    var target = $(event.target).('li');
    console.log(target);   // will always be parent li element itself?
});

Thanks

+1  A: 

In the handler, this will refer to the li element.

$('#foo').delegate('li', 'click', function(event) {
    var target = $(this);
    console.log(target);   // will always be parent li element itself?
});
patrick dw
A: 

var target = $(this) should be one way--that's how I usually do it. $(event.target).parents("li") would be another, but you might pick up more than you expect.

joelt
that should be `parent`, `parents` would return all `li`'s if youre nesting `ul`s for a menu for example. parent will return only the first one matching the selector.
prodigitalson
@prodigitalson - That's not quite right. jQuery's `.parent()` method looks at only the immediate parent. If you pass a selector, and the immediate parent doesn't match it, you get an empty jQuery object.
patrick dw