e.target.parentNode return this
<div class="quantity">
<span class="glyphicon glyphicon-minus-sign"></span>
<span class="product_Count"> 4 </span>
<span class="glyphicon glyphicon-plus-sign"></span>
</div>
So how can we change count of "product_count" class? Remember there are multiple div same as above so how can we change count of only this div after getting it from e.target.parentNode?
e.target.parentNode will return the parent of the target element which triggered the event. On the returned parent element, you can use any of the following functions to select the .product_Count element
.querySelector('.product_Count');.getElementsByClassName('product_Count')[0];Above functions will select the .product_Count element within the element returned by e.target.parentNode. To update the count, use any of the following:
.innerHTML.textContentAs mentioned in your question that there are multiple div elements with .quantity class, so instead of adding event listeners on individual .glyphicon elements, you could take advantage of event bubbling and add a single click event listener on the parent element of all the .quantity elements.
See the snippet below which shows how you could increment/decrement count when there are more than one .quantity elements
const container = document.querySelector('.container');
container.addEventListener('click', (e) => {
const target = e.target;
if (target.matches('.glyphicon')) {
const parentEl = target.closest('.quantity');
const countEl = parentEl.querySelector('.product_Count');
let count = Number(countEl.textContent);
if (target.matches('.minus')) {
count -= 1;
} else {
count += 1;
}
countEl.textContent = count;
}
});
.glyphicon {
border: 1px solid;
padding: 0 5px;
cursor: pointer;
}
<div class="container">
<div class="quantity">
<span class="glyphicon minus">-</span>
<span class="product_Count"> 4 </span>
<span class="glyphicon plus">+</span>
</div>
<br/>
<div class="quantity">
<span class="glyphicon minus">-</span>
<span class="product_Count"> 2 </span>
<span class="glyphicon plus">+</span>
</div>
</div>
If you don't want the count to be negative, make sure that you only update the count if after decrement, its value is not less than zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With