Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery event.target to work with children

Tags:

jquery

dom

My question refers specifically to http://api.jquery.com/event.target/#example-1

If you use a span in the <li> or other tag to change the style such as <b> as I have done here, that part of the element won't trigger the JQuery function to toggle it's children. How might one go about making this work?

HTML:

<ul>
    <li><b>This doesn't work,</b> this does
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>
</ul>

JavaScript:

function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {
    $target.children("ul").toggle();
  }
}
$("ul").click(handler).find("ul").hide();
like image 893
SteveC Avatar asked Jul 19 '13 23:07

SteveC


People also ask

How do you get children of children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

Is event target deprecated?

target are obsolete, not that Event. target itself is obsolete. The DOM (Living Standard) specification is not marked as obsolete and you should use that definition.

What is jQuery event target?

The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.

What is the use of event target?

Definition and Usage The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.


1 Answers

To keep using your current form, I'd suggest using closest():

function handler(event) {
    $(event.target).closest('li').children("ul").toggle();
}
$("ul").click(handler).find("ul").hide();

JS Fiddle demo.

Though for my own use I'd prefer:

$('li').on('click', function(e){
    e.stopPropagation();
    $(this).find('ul').toggle();
});

JS Fiddle demo.

References:

  • closest().
  • on().
like image 102
David Thomas Avatar answered Sep 24 '22 14:09

David Thomas