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.
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>
You can use pointer-events css attribute to achieve this.
#something li>span {
pointer-events: none
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.