Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate handler and inner children clicked

Tags:

jquery

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

like image 681
user246114 Avatar asked Nov 05 '22 09:11

user246114


1 Answers

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?
});
like image 182
user113716 Avatar answered Nov 12 '22 10:11

user113716