# E-commerce template : function add cart shopping Js

**URL:** <https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249>\
**Category:** General\
**Created:** [May 13, 2020, 3:32pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249 "2020-05-13T15:32:21Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![camcode](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camcode/32/113316_2.png) [@camcode](https://forum.freecodecamp.org/u/camcode)\
**Post date:** [May 13, 2020, 3:32pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/1 "2020-05-13T15:32:21Z")

</div>

Hi,

I created this simple e-commerce model and I’m having trouble adding the product to the cart.  
I have created a counter function which must be displayed in a div that I added in the upper right corner where the shopper image is located, but my code does not work, the color of the button changes.

I have tried using getElementById it works but only for the first product, while the others does not work.

```auto
// to fix 
let addButton = document.querySelector("btn-add"),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
addButton.addEventListener("click", function(){
  
  const changeColorBtn = document.body.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    document.body.style.backgroundColor = "green";
  }
 else{
   document.body.style.backgroundColor = "#2c3632";
 }
  count += 1;
  shopping_cart.innerHTML = count  
});

```

This is my pen:

> **[e-commerce template](https://codepen.io/camilco/pen/GRpGNGp?editors=0110)**
>
> ...

P.S . To anyone who answers me, would you suggest me to study DOM JS better?If you suggest me resources that are understandable and simple, I have been banging my head for a long time but I still struggle.

Thanks,  
CamCode

---

<div class="post-metadata">

**Author:** ![Catalactics](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/catalactics/32/151364_2.png) [@Catalactics](https://forum.freecodecamp.org/u/Catalactics)\
**Post date:** [May 13, 2020, 3:37pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/2 "2020-05-13T15:37:40Z")

</div>

I do not know what are you trying to grab from the HTML, but this line is trying to access the `<body>` tag, and not the button.

> [@camcode](#):
>
> document.body.style.backgroundColor;

It is okay to use this, but its recomended to declare each variable individually so other people can read it easily.

> [@camcode](#):
>
> let addButton = document.querySelector(“btn-add”), shopping\_cart = document.getElementById(“shopping-add”), count = 0;

Yes, it is recommended to study DOM JS if you want to make your website interactive, and if you want to manipulate the HTML DOM.

> [@camcode](#):
>
> To anyone who answers me, would you suggest me to study DOM JS better?If you suggest me resources that are understandable and simple, I have been banging my head for a long time but I still struggle.

---

<div class="post-metadata">

**Author:** ![camcode](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camcode/32/113316_2.png) [@camcode](https://forum.freecodecamp.org/u/camcode)\
**Post date:** [May 13, 2020, 3:40pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/3 "2020-05-13T15:40:35Z")

</div>

Like this ?

```auto
document.addButton.style.backgroundColor;

```

---

<div class="post-metadata">

**Author:** ![Catalactics](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/catalactics/32/151364_2.png) [@Catalactics](https://forum.freecodecamp.org/u/Catalactics)\
**Post date:** [May 13, 2020, 3:42pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/4 "2020-05-13T15:42:07Z")

</div>

If you want to access the button, You already declared the variable up here

> [@camcode](#):
>
> addButton = document.querySelector(“btn-add”)

So you can just use the variable and not `document`, because `document` means to grab the whole document again.

```auto
addButton.style.backgroundColor;

```

---

<div class="post-metadata">

**Author:** ![skaparate](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/skaparate/32/125896_2.png) [@skaparate](https://forum.freecodecamp.org/u/skaparate)\
**Post date:** [May 13, 2020, 3:45pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/5 "2020-05-13T15:45:34Z")

</div>

Hello!

> [@camcode](#):
>
> I have tried using getElementById it works but only for the first product, while the others does not work.

That’s because the `querySelector` is not actually querying the existing `class`, it’s instead querying for a tag called `btn-add`.

On the other hand, `id`s are meant to be unique, hence you should change the `id` attribute for `class` instead and using the class selector, not a tag. Look at these differences:

```auto
btn-add // This is a tag selector, like a div or any other tag.
#btn-add // This is an ID selector, querying the attribute id of a single element
.btn-add // this is a class selector, in other words, queries the class attribute.

```

Finally, there’s a difference between `document.querySelector` and `document.querySelectorAll`:

```auto
document.querySelectorAll('.btn-add') // Returns an array
document.querySelector('.btn-add') // Returns a single element

```

I hope it helps 🙂,

Regards!

**Edit**

For a better understanding [read this entry on CSS Selectors in the Free Code Camp Blog](https://www.freecodecamp.org/news/css-selectors-cheat-sheet/).

---

<div class="post-metadata">

**Author:** ![camcode](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camcode/32/113316_2.png) [@camcode](https://forum.freecodecamp.org/u/camcode)\
**Post date:** [May 13, 2020, 3:55pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/6 "2020-05-13T15:55:21Z")

</div>

Ok I fixed my code but doesn’t work yet

```auto
let addButton = document.querySelectorAll('.btn'),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
addButton.addEventListener("click", function(){
  
  const changeColorBtn = addButton.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    addButton.style.backgroundColor = "green";
  }
 else{
   addButton.style.backgroundColor = "#2c3632";
 }
  count += 1;
  shopping_cart.innerHTML = count  
});

```

😔

---

<div class="post-metadata">

**Author:** ![skaparate](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/skaparate/32/125896_2.png) [@skaparate](https://forum.freecodecamp.org/u/skaparate)\
**Post date:** [May 13, 2020, 4:17pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/7 "2020-05-13T16:17:51Z")

</div>

> [@camcode](#):
>
> Ok I fixed my code but doesn’t work yet

Yes, I know, but try to understand what’s happening 🙂.

```auto
let addButton = document.querySelectorAll('.btn');
// Remember that I said this returns an array?
// Arrays don't have an 'addEventListener' method.

```

Take a look a this code ([you can see it working here](https://jsfiddle.net/skaparate/p2euLtsk/5/)):

```auto
<body>
<button id="special-button" class="btn">
One
</button>
<button class="btn">
Two
</button><button class="btn">
Three
</button>
<script>
/**
 * A simple function to display which target was clicked
 *
 * @param e The event data.
 */
function handleClick(e) {
	console.log('Element:', e.target);
}

const special = document.querySelector('#special');
const btns = document.querySelectorAll('.btn');

special.addEventListener('click', handleClick);

// Error! Arrays do not have the 'addEventListener' method:
// btns.addEventListener('click');

// Instead we must iterate the array and assign each
// button a listener:
btns.forEach(i => i.addEventListener('click', handleClick));
</script>
</body>

```

Read the comments and try to understand what happens 🙂.

---

<div class="post-metadata">

**Author:** ![camcode](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camcode/32/113316_2.png) [@camcode](https://forum.freecodecamp.org/u/camcode)\
**Post date:** [May 13, 2020, 4:31pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/8 "2020-05-13T16:31:53Z")

</div>

I also thought of iterating but it doesn’t work the same maybe I was wrong to write for loop.

```auto
let addButton = document.querySelectorAll('.btn'),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
for(let i = 0; addButton.length; i++){
addButton.addEventListener("click", function(){
  const changeColorBtn = addButton.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    addButton[i].style.backgroundColor = "green";
  }
 else{
   addButton[i].style.backgroundColor = "#2c3632";
 }
  count += 1
  shopping_cart.innerHTML = count
} 
)}

```

---

<div class="post-metadata">

**Author:** ![camcode](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camcode/32/113316_2.png) [@camcode](https://forum.freecodecamp.org/u/camcode)\
**Post date:** [May 13, 2020, 5:14pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/9 "2020-05-13T17:14:47Z")

</div>

UPDATE: I resolved thanks to help from another

I was definitely wrong to write the loop condition I had to use foreach and not a simple loop and then I had to use textContent instead of innerHTML.

```auto
let addButtons = document.querySelectorAll(".btn"),
  shopping_cart = document.getElementById("shopping-add"),
  count = 0;

addButtons.forEach((addButton) => {
  addButton.addEventListener("click", function () {
    const changeColorBtn = addButton.style.backgroundColor;

    console.log(changeColorBtn);

    if (!changeColorBtn || changeColorBtn === "rgb(44, 54, 50)") {
      addButton.style.backgroundColor = "green";
    } else {
      addButton.style.backgroundColor = "rgb(44, 54, 50)";
    }

    count += 1;

    shopping_cart.textContent = count;
  });
});

```

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [June 1, 2021, 6:53pm UTC](https://forum.freecodecamp.org/t/e-commerce-template-function-add-cart-shopping-js/388249/10 "2021-06-01T18:53:48Z")

</div>

Closed on June 1, 2021, 6:53pm UTC


