Search code examples
javascriptjquerydom-eventsevent-propagation

Can't get JS to bubble event


I've got a structure as in this fiddle: https://jsfiddle.net/Arne651/s8wbeyh5/11/

<ul id="ul">
  <li class="test">
    <p>
      Some text
    </p>
  </li>
  <li class="test">
    <p>
      Some text
    </p>
  </li>
  <li class="test">
    <p>
      Some text
    </p>
  </li>
</ul>

I've got an event on a <ul> element, in which im trying to do something with the <li> element that was clicked. This <li> element contains a <p> element and the event doesn't seem to bubble upwards.

let ul = $("#ul")
ul.on("click", function(e) {
    let clicked = $(e.target)
    console.log(clicked)
    if (clicked.hasClass("test")) {
        console.log("li triggered")
    }
})

I don't want events on all the <li> elements because the list can get quite long and a single event feels neater.


Solution

  • When clicking the text, the target is the p tag.

    Getting the closest li might not be the best way to do this but this works.

    ul.on("click", function(e) {
        let clicked = $(e.target).closest('li');
        console.log(clicked);
        if (clicked.hasClass("test")) {
            console.log("li triggered");
        }
    });