humleAfriqan
humleAfriqan

Reputation: 59

Selective event listening on DOM elements

I have this HTML code

<ul id='something'>
    <li class="listItem"><span class="name">Somename1</span> <span class="number">4</span></li>
    <li class="listItem"><span class="name">Somename2</span> <span class="number">4</span></li>
    <li class="listItem"><span class="name">Somename3</span> <span class="number">4</span></li>
</ul>

I also have this JavaScript code that attaches an event listener to the ul tag like this

let itemList = document.getElementById('something')
itemList.addEventListener('click', event => {
    ....
})

I want to use event bubbling to access the li elements but the span elements always get the event in the browser. How do I disable the event listener on the span elements? How can I use conditional statement to access only the immediate child elements of the ul tag. Is there a better way to go about this than what I'm doing? Please I'm using pure JavaScript.

Upvotes: 0

Views: 48

Answers (2)

Prajwal
Prajwal

Reputation: 198

You can use pointer-events css attribute to achieve this.

#something li>span {
  pointer-events: none
}

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

Use Element.closest() on the event's target to find the closest <li> parent element (or itself if the li is clicked directly):

let itemList = document.getElementById('something')
itemList.addEventListener('click', event => {
  const li = event.target.closest('li');

  if (!li) return;

  console.log(li);
})
<ul id='something'>
  <li class="listItem"><span class="name">Somename1</span> <span class="number">4</span></li>
  <li class="listItem"><span class="name">Somename2</span> <span class="number">4</span></li>
  <li class="listItem"><span class="name">Somename3</span> <span class="number">4</span></li>
</ul>

Upvotes: 3

Related Questions