How to Get into a Nested Class in JavaScript

I'm struggling to articulate my question, but I know there's a solution out there. I have profile cards in HTML, each with the class "card" containing two numbers. My goal is to display a progress bar specific to the % relationship of these numbers within EACH individual card.

Here's an example of my code:

<div class="card">
<p class="nameTitle">NAME 1</p>
<p class="cardTarget">20</p>
<p class="cardCurrent">10</p>
<div class="progBar"></div>
</div>

<div class="card">
<p class="nameTitle">NAME 2</p>
<p class="cardTarget">20</p>
<p class="cardCurrent">5</p>
<div class="progBar"></div>
</div>

I want Javascript to access the cardTarget and cardCurrent for nameTitle: NAME 1, then calculate a percentage and output it to progBar of that same card. This should be done for each card like nameTitle: NAME 2.

This means the progBar for nameTitle: NAME 1 should be set at 50%, and for nameTitle: NAME 2 it should be at 25%.

I understand how to access elements and perform calculations for percentages, but what I'm struggling with is how to bind these elements to each card individually without affecting other cards since they share the same class names.

I hope this explanation is clear, and thank you in advance for your assistance.

Answer №1

If you're searching for a way to locate an element within another element, Element#querySelector is what you're looking for. It also offers Element#querySelectorAll to find a list of elements.

For example, to update those cards:

document.querySelectorAll(".card").forEach(card => {
    const cardTarget = card.querySelector(".cardTarget");
    const cardCurrent = card.querySelector(".cardCurrent");
    const progBar = card.querySelector(".progBar");
    const percent = (cardCurrent.textContent / cardTarget.textContent) * 100; // Replace as needed
    progBar.setSomethingToReflectThatPercentage();
});

Check out this live example:

setTimeout(() => {
  document.querySelectorAll(".card").forEach(card => {
      const cardTarget = card.querySelector(".cardTarget");
      const cardCurrent = card.querySelector(".cardCurrent");
      const progBar = card.querySelector(".progBar");
      const percent = (cardCurrent.textContent / cardTarget.textContent) * 100; // Replace as needed
      progBar.innerHTML = percent;
  });
}, 500);
<div class="card">
<p class="nameTitle">NAME 1</p>
<p class="cardTarget">20</p>
<p class="cardCurrent">10</p>
<div class="progBar">--</div>
</div>

<div class="card">
<p class="nameTitle">NAME 2</p>
<p class="cardTarget">20</p>
<p class="cardCurrent">5</p>
<div class="progBar">--</div>
</div>


Just a heads up: This code snippet uses forEach on the NodeList from querySelectorAll. Keep in mind that if you need to support older browsers, you may need to polyfill it. Check out this answer for more information.

Answer №2

Here is a possible starting point for your project. Please note that the positioning values are somewhat random, and you may want to customize the styling to suit your needs:

for (const e of document.getElementsByClassName("card")) {
  const target = +(e.querySelector(".cardTarget").innerText);
  const current = +(e.querySelector(".cardCurrent").innerText);
  const bar = e.querySelector(".progBar");
  bar.style.width = current / target * 300 + "px";
  bar.innerText = current * 5 / (target * 5) * 100 + "%";  
}
.progBar {
  height: 20px;
  background: #000;
  color: #fff;
}
<div class="card">
  <p class="nameTitle">NAME 1</p>
  <p class="cardTarget">20</p>
  <p class="cardCurrent">10</p>
  <div class="progBar"></div>
</div>

<div class="card">
  <p class="nameTitle">NAME 1</p>
  <p class="cardTarget">20</p>
  <p class="cardCurrent">5</p>
  <div class="progBar"></div>
</div>

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

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

I am having trouble getting the Express Router delete method to function properly when using mongoose with ES8 syntax

I was working on this code snippet : router.delete('/:id', (req, res) => { Input.findById(req.params.id) .then(Input => Input.remove().then(() => res.json({ success: true }))) .catch(err => res.status(404).json({ success: f ...

AngularJS: Unable to locate element using getElementById function

Using a third party JavaScript application, I have integrated and invoked a function within one of my AngularJS factories. This function requires the id of a DOM element as a parameter, as it manipulates this element. ThirdPartyApp.doSomething("#elementId ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Using JavaScript to save coordinates as a 2D Vector Object

Which option is optimal for both memory usage and calculation speed? new Float32Array(2); new Float64Array(2); {x: 0, y: 0}; [0, 0]; It's clear that option 1 uses less memory than option 2, but what about speed? Are calculations faster with 32 bits ...

Is the user's permission to access the Clipboard being granted?

Is there a way to verify if the user has allowed clipboard read permission using JavaScript? I want to retrieve a boolean value that reflects the current status of clipboard permissions. ...

Developing an object that displays animated effects when modifying its properties, such as visibility, and more

Exploring the realm of animations in JavaScript and AngularJS has led me to the idea of creating a unique JavaScript object. Imagine having the ability to define an object where setting an attribute like obj.visible = true Would automatically make the ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Restriction on Google Maps API: Mouseover functionality is limited to specific hours of the day

Throughout my programming journey, I've encountered some weird errors, but this one takes the cake. I'm stumped as to why it's happening. Here's the situation: My application is supposed to fetch data from a MySQL Database and display ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

javascript implementing optional chaining for a single parameter

Is it possible to implement optional chaining on a single parameter? setAllProperties( Object.values(users).flatMap(({ properties }) => Object.values(properties) ) ); I am looking for a way to ensure that the properties folder exists in ...

Executing successive setState() calls within a React method: Achieving "synchronous" behavior

During a recent issue in my React application, I encountered a scenario where I needed to make multiple setState() calls within one method and ensure that certain code executed AFTER the states were set. The following code snippet showcases a Dialog box ut ...

Executing a child function from the parent component in React 16

Ever since I upgraded to react 16, I've been encountering null in my console.log(this.child) The Main Component import EditReview from './partials/editReview' class VenueDetails extends Component { constructor(props) { super(props) ...

Using electron cookies in Angular involves integrating Electron's native cookie functionality into an

I am currently dealing with electron and looking to implement cookies conditionally in my project. If the application is built using electron, I want to utilize Electron Cookies; otherwise, I plan to use Angular Cookies. However, I'm encountering diff ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

The Antd Tooltip becomes unresponsive when a component is clicked and moved

Having an issue with a button that has an Antd tooltip, here is the setup: <Tooltip title="Some text"> <button onClick={openNotes}><Icon icon="notes" /></button> </Tooltip> Upon clicking the button, the ...

What is the best way to extract an object from an array that only includes one element, and that element is an object?

Here is the output of my updated function: db.collection('SOCIAL').get().then((snapshot) =>{ snapshot.docs.forEach(doc => { tempData.push(doc.data()) }) return tempData }) I want to store these valu ...