I would like to set a click event listener in vanilla javascript on an UL , then on a click inside of that, I want to get the element clicked, check to see if it is an LI, if it is not - go up the parentNode until LI is reached, if it is - get it, if its not - stop at the UL.
Jsfiddle - https://jsfiddle.net/urbbsu0t/4/
I tried many methods and read a few articles, but everything I find works when there are no nested elements, ie if I have a single element inside the LI. But how can I compare them if I have many children?
Here is an example of an LI element
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt dicta
laborum, excepturi tenetur vero cum!</p>
<button>button goes here</button>
</div>
</li>
const services = document.querySelector('.services');
services.addEventListener('click', function(e) {
})
.services {
display: flex;
justify-content: space-between;
}
.service {flex 1 30%; max-width: 30%;}
<ul class="services">
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus sequi ab quod.</p>
<button>button goes here</button>
</div>
</li>
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum, officiis?</p>
<button>button goes here</button>
</div>
</li>
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt dicta laborum, excepturi tenetur vero cum!</p>
<button>button goes here</button>
</div>
</li>
</ul>
You can use Element.closest()
:
The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null.
Example:
const services = document.querySelector('.services');
services.addEventListener('click', function(e) {
const li = e.target.closest('.service');
if(li) li.style.color = 'red';
});
.services {
display: flex;
justify-content: space-between;
}
.service {flex 1 30%; max-width: 30%;}
<ul class="services">
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus sequi ab quod.</p>
<button>button goes here</button>
</div>
</li>
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum, officiis?</p>
<button>button goes here</button>
</div>
</li>
<li class="service">
<div class="service-body">
<h1>Title goes here</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt dicta laborum, excepturi tenetur vero cum!</p>
<button>button goes here</button>
</div>
</li>
</ul>