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

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Issues with websockets functionality have been reported specifically in Firefox when trying to connect to multiple

I am currently working on a websocket client-server application. The client code is as follows: const HOST = "wss://localhost:8000"; const SUB_PROTOCOL= "sub-protocol"; var websocket = new WebSocket(HOST, SUB_PROTOCOL); websocket.onopen = function(ev ...

Issues with Bootstrap tabs loading jQuery and Ajax are preventing the proper functionality

I am currently facing an issue with a tab pane designed using Bootstrap. The problem arises when attempting to load external pages into the tabs through Ajax using a jQuery script. While the ajax script successfully loads the content of the pages, I am en ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax.. This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying the ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

After a single click, the functionality of jquery.nav.js seems to be malfunctioning

Encountering an error message: Uncaught TypeError: Cannot read property 'top' of undefined(…) jquery.nav.js:183 In an effort to convert my web app into a Single Page Application (SPA) using the jquery.nav.js library (available at https://githu ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

Having trouble with the authorization aspect of Next Auth. The error message reads: "NextAuth.js does not support the action api with HTTP GET method

Recently, I've been encountering a puzzling error with my Next.js app authentication. It seems that I am unable to authenticate with the provided credentials. After reviewing the documentation, everything appears to be correct on my end. Additionall ...

Clicking on the menu in mobile view will cause it to slide upward

I have implemented sticky.js on my website and it is working well. However, when I resize the browser to mobile view and click the main menu button, it goes up and I am unable to close it. I have to scroll up to see it again. How can I make it stick to the ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Is there a way to toggle a single Reactstrap Collapse component?

Currently, I am working on a Next.JS application that displays a list of Github users. The goal is to have each user's information box toggle open and close when clicked, using Reactstrap's Collapse component. However, the issue I'm facing i ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Email notification will be sent upon form submission to Firestore

I'm currently designing a website for booking reservations through an HTML form, with data submission to firestore. Upon submission, a confirmation email is sent to the customer. Below is the code snippet I am using to achieve this: var firestore = fi ...

Can a MS Teams Bot be triggered to show a botMessagePreview from a task or submit activity rather than a composeExtension or submitAction activity?

As I develop a messaging extension in Teams that utilizes task modules and sends adaptive cards, I am faced with the challenge of invoking the same task module from both a messaging extension command and a button on an adaptive card sent to the user. The ...

Is it possible to automatically access the most recent Beta build through package.json and npm?

We are currently working on a project that has a specific dependency requirement for the latest beta build from an npm library. However, there are also -dev builds within the library. For instance, in the "x-library" there might be versions like: "1.2.3- ...

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...