Putting all elements of a certain class in an array

Hello everyone, I am trying to calculate the price of the total order on my website.
So I am trying to get all elements with the class “cartprice” and add them to an array, to later add them all together.
On this I am stuck.

 if  (this.props.cart.length !== 0) {
      var pricesvar = document.querySelectorAll('.cartprice')
      let pricearray =  ''
pricearray.push(pricesvar)
console.log(pricearray)
    }

How would you go about doing this?
Thanks in advance for your help.

Hello there.

You have defined a string, but called it an array which is what it should be.

.push() is an array method. Not for strings.

Hope this helps

1 Like

Yeah that was a very dumb mistake. Thanks for catching that!
Now if you have time, would you help me with the next part?
I was expecting to get a value of the element by putting .value on the end of the query selector but instead I am getting undefined.
How do I get an array of values?

console.log(pricesvar) to get an idea of the object structure. Without seeing the rest of your code, I cannot be sure what document.querySelectorAll('.cartprice') is returning.

What type of element is it and when are you trying to get the value?

Also, considering you have this.props in your code I’m assuming this is a React app, if so, you should do it the React way if you can (basic form stuff).


    }
     componentDidMount() {
    if  (this.props.cart.length !== 0) {
      var pricesvar = document.querySelectorAll('.cartprice')
      let pricearray =  []
pricearray.push(pricesvar)
console.log(pricearray)
    }
     }
     
    
    
    
     

    render()
    
   
    { 
        
        if (this.props.cart.length !== 0) { 
            var cartitems = this.props.cart.map(function(
              cartitems
            ) 
            
            {
              return (
                  
                      <div className="col-sm-12  cartitem" key={cartitems[1]}>
                      
                        <img src={cartitems[2]}  id={cartitems[2]}  alt={cartitems[1]} className="cart-image"></img>
                    
                        <h5 className="" >{cartitems[1]}</h5>
                       <div className="pricebox">
                        <p  className="cartprice">{cartitems[0]}</p>
                        
                      </div>
                        
                       
                        
                        
                      </div>
                      
                   
              );
            });
          } else return <h1 className="nocart">Add items to your cart and they will appear here.</h1>;
        
          return (
            <div className="cart-container">
      
      
        
         {cartitems}
         <div className="cartfooter">
         <h4 className="yourtotal">
          Your total: 
          $ {this.props.total}
      </h4> 
       <PaypalButton className="checkoutbutton" total={this.props.total} />
              </div>
         </div>
          )
    }
    
    
    

Here is the full code.
It is console.log-ing an array that has 2 nodelist in it. I have no idea how to work with a nodelist.
I just want an array of the values of each of the mapped elements.
If you need to see the full project: https://github.com/Imstupidpleasehelp/fitnesswebsiteagain

Seeing what was logged would be more useful…

Otherwise, I suggest you give this a read, anyway: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement

1 Like

1
It won’t let me copy for some reason, but this is what is logging.

A p element do not have a value property, you can use textContent or innerHTML

1 Like

Thank you all for your continued help.
I also had the thought to use innerHTML, Where exactly do I put the .textContent?

if  (this.props.cart.length !== 0) {
      var pricesvar = document.querySelectorAll('.cartprice')
      let pricearray =  []
pricearray.push(pricesvar.textContent)
console.log(pricearray)
    }

Doing it like this I got undefined. I’ve put it in a few places and it is just returning undefined.

pricesvar is a NodeList as returned by querySelectorAll, it does not have that property. Each p element has the property.

Edit: Looking at your code. Is there a reason why you never installed (or at least use) Prettier? Your code really needs to be formatted and if you can’t be bothered to do it you should just let an extension do it for you.

1 Like

I am still very new to this. I installed prettier but never ran it.
With all the info I got in this thread I should be able to solve the rest of this on my own.
Thanks for all your help.

I’m going to harp on this again like I did last time, sorry in advance.

Just like last time you are missing dependencies in your package.json. It really makes it hard for others to collaborate with you if you do not set the projects up so they can just npm install it. You are missing so many dependencies that we can’t compile the app without installing and/or commenting out a bunch of stuff.

I would suggest this (if not now then soon). Backup the project first just in case. Now delete the node_modules folder and try running npm install, now run npm start. Fix all the missing dependencies until you can just clone the repo and run npm install without it failing to compile. That is how your project should be set up.

In the VS Code setting you can set it to just auto format on save.

Don’t worry about harping, I certainly need it. I remember last time I did these exact steps (i have 3 backups now) where I deleted the package.json and did npm install. And this cleaned up a lot of the npm vulnerabilities. I thought now it would be easier to work with but I guess I still have work to do.
And I have since configured prettier to work on save. Thanks for the bit of advice I had no idea you could do that.
Thanks for working with my trash code, I am almost done 1000% because of this website.

All beginner code is bad, in 6 months you will look back at some code you wrote and think to yourself “what the hell was I doing here?”. It’s just part of the process and totally normal. We do not have any expectations for you to write “great code” as a beginner. So don’t worry and keep asking for help when you need it.

Did you mean you deleted the node_moduels folder?

Because package.json has (should have) all the dependencies. Well, not the actual code of the dependencies just instructions for npm. When you run npm install it looks at the package.json file and installs all the dependencies listed, all the actual code of the dependencies is in the node_moduels folder.

This is why deleting the node_moduels folder and running npm install will put you where everyone else is that clones your repo. You can test this by cloning your own repo into some folder and run npm install. You should now be able to just run npm start and everything should work.

Here is the fCC curriculum on npm, might be worth a look if you have not done the challenges.

You also have to remember to commit any changes and push the package.json file.

1 Like

I am sorry to bring back thread that’s a bit old. But I am honestly stumped on this even after reading the documentation posted here.
So far I am iterating over the html collection with a for loop
The problem is it is returning an empty array with a length of 0. and I can’t figure out why.

componentDidMount() {
    if (this.props.cart.length !== 0) {
      var pricevar = document.getElementsByClassName("cartprice");
var i;
let pricearray =[]
for (i = 0; i < pricevar.length; i++) {
  pricevar[i].textContent = pricearray;
}console.log(pricearray)
  }
}

You are assigning an empty array to textContent

pricevar[i].textContent = pricearray;

I assume you want to add the textContent to the array.

pricearray[i] = pricevar[i].textContent;

or

pricearray.push(pricevar[i].textContent)

BTW, forEach works with NodeList.

pricevar.forEach(priceElement => pricearray.push(priceElement.textContent));
1 Like

You are my savior. Thank you.