What is the best way to retrieve a specific property or attribute of a specific div element after obtaining it from e.target.parentNode?

e.target.parentNode will return this element.

    <div class="quantity">
        <span class="glyphicon glyphicon-minus-sign"></span>
        <span class="product_Count"> 4 </span>
        <span class="glyphicon glyphicon-plus-sign"></span>
    </div>

Now, the challenge is to change the count of the "product_count" class in only this specific div after identifying it through e.target.parentNode. This task becomes more complex considering there are multiple similar div elements like the one shown above. How can we accurately target and modify the count of just the desired div?

Answer №1

e.target.parentNode retrieves the parent element of the target that triggered the event. You can then utilize any of the following methods to select the .product_Count element:

  • .querySelector('.product_Count');
  • .getElementsByClassName('product_Count')[0];

The above functions will target the .product_Count element within the parent element returned by e.target.parentNode. To modify the count, you can use either of the following:

  • .innerHTML
  • .textContent

If there are multiple div elements with the .quantity class, instead of adding event listeners individually on each .glyphicon element, you might consider leveraging event bubbling and attaching a single click event listener to the parent element encompassing all .quantity elements.

Refer to the demonstration below showcasing how you can increase/decrease the count when there are numerous .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>

To prevent negative counts, ensure that count updates only occur if the value does not go below zero after decrementing.

Answer №2

Perhaps you are looking to increase the product count when the plus symbol is clicked? You can achieve this by utilizing e.target.nextElementSibling and e.target.previousElementSibling to target the product count element. Then, simply update its text using `elem.text = 'foobar'.

If they happen to click the minus symbol,

function onMinusClicked(event){
  let num = parseInt(event.target.nextElementSibling.text);
  event.target.nextElementSibling.text = num - 1;
}

For increasing the count when the plus symbol is clicked,

function onPlusClicked(event){
  let num = parseInt(event.target.previousElementSibling.text);
  event.target.previousElementSibling.text = num + 1;
}

This method will work seamlessly even if there are multiple divs with the class name quantity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Having trouble installing Bootstrap using the `npm i bootstrap` command? It seems like the

The npm i bootstrap command is not working when trying to install Bootstrap. Nothing is being added to the packages.json file or node_modules directory. Here are the dependencies listed in the package.json file: "dependencies": { "@angu ...

The alignment issue persists when attempting to set 'relative' on the parent and 'absolute' on the inner element in a Bootstrap column for bottom alignment

Here is a snippet of my basic HTML code: <div class = "row"> <div class = "col-xs-8"> <p>long long long long text that generates a taller column</p> </div> <div class = "col-xs-4"> <p> ...

What steps can be taken to restrict a user's access to a route through URL parameters?

I am currently developing an Express application that generates and exports a document based on the selections made by a user from two dropdown menus. The values selected in the dropdowns are passed as route parameters after the user clicks a button, trigg ...

Tips for Implementing {{ }} within Angular Filters in Nested ng-repeat statements

I am looking to incorporate {{ }} within the Angular "filter" filter, specifically while nested inside an ng-repeat. Let's consider the relationship below: var categories = [ {"title":"land"}, {"title":"sea"}, {"title":"air"} ]; var vehi ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Following a Node/Npm Update, Sails.js encounters difficulty locating the 'ini' module

While developing an application in Sails.js, I encountered an authentication issue while trying to create user accounts. Despite my efforts to debug the problem, updating Node and NPM only resulted in a different error. module.js:338 throw err; ...

Tips for preventing NextJS from including a dynamically imported component in the main _app.js bundle while utilizing Module Aliases

Currently, I am in the process of transforming some shared-ui components into dynamically imported ones within NextJS 11. I have set up module aliases using @nx/next:library, for example @my-site/shared-ui, all exported from an index.ts file as shown belo ...

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

Exploring Parameters to Customize Search Results in React

I am currently working on implementing a data filtering system based on user input. However, it seems that the data disappears whenever I enter something into the search box. Upon inspecting the dev tools, I can see that the query state is being saved pro ...

What is the best way to add clickable links to 3D objects and meshes with ThREE?

My goal is to create a simple box that can act as a link when clicked. This seemingly straightforward task has proven difficult for me, so I would greatly appreciate any assistance. Despite my efforts to troubleshoot and research online, I have not been ...

Error message: When attempting to create dynamic inputs in React, an error occurs stating that instance.render is not

I encountered an issue while attempting to create dynamic inputs in React. The error message 'TypeError: instance.render is not a function' keeps popping up. import React, { Component } from 'react'; import Input from '../../Ui/Inp ...

What is the best way to position a <td> element within a table row underneath another <td>?

Looking for a solution to ensure Content 3 appears below Content 2 in this block of HTML. Content 1 is extensive and extends far down the page. <table> <tr> <td>(Content 1)</td> <td>(Content 2)</td> ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application. var app = angular.module('app', []); app.contr ...

What is the best approach for designing the architecture of a server-side node.js application?

Can you recommend a suitable architecture or pattern for building server-side applications using node.js? For the front-end, I plan on implementing a backbone.js MVC framework and utilizing websockets for communication. If you could provide some examples ...

"Learn how to dynamically update the user interface in express.js using handlebars without having to refresh the

As a newcomer to using express.js and Handlebars, I am faced with the challenge of implementing autocomplete functionality. Specifically, I want to enable autocompletion in a text input field without triggering a page refresh when users interact with it. C ...