Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we access some property/attribute of particular div after getting it from e.target.parentNode

Tags:

javascript

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?

like image 554
Safwan Bardolia Avatar asked Dec 17 '25 11:12

Safwan Bardolia


1 Answers

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
  • .textContent

As 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.

like image 190
Yousaf Avatar answered Dec 20 '25 01:12

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!