JavaScript - Problem with adding HTML element only on lastchild

Hello.
I am js newbie, and I am trying to create movie shop just for exercise. I have list of 8 movies from some api, and I added some genereal stuff about each movie. I also added ‘‘Kupi me’’ button which means ‘‘buy me’’.
When I click on that button I create new HTML element and I add it to shooping card. I also menaged to create HTML element which contains price, some text and Chekout button. I want this element only to be attached to last movie on the list. I can’t make to work, only to add it on every movie.

Here is link to imgur where you can see better what I am talking about.

Here is JS, HTML and CSS if you can’t figure it it just from JS.

const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": "cd782e9b03mshbd50bac036f1802p16179djsn48c38f33f263",
    "X-RapidAPI-Host": "online-movie-database.p.rapidapi.com",
  },
};

const main = document.querySelector(`.prozor`);
const shoopingCart = document.querySelector(`.shooping-cart`);

fetch(
  "https://online-movie-database.p.rapidapi.com/auto-complete?q=hacker",
  options
)
  .then((response) => response.json())
  .then((data) => {
    const list = data.d;
    list.map((item) => {
      const name = item.l;
      const rank = item.rank;
      const price = Math.floor(rank / 100);
      const poster = item.i.imageUrl;
      const movie = ` <div class="movie">
               <img src=${poster} alt="${name}" />
                           <div class="movie-info">
                              <h3>${name}</h3>
                              <span>#${rank}</span>
                            </div>
                            <div class="kupi">
                              <button class="addToBag">Kupi film</button>
                              <span>${price} HRK</span>
                            </div>
                    </div>`;
      main.innerHTML += movie;

      //---------------------------------- add to basket --------------------------//

      const button = document.querySelectorAll(`.addToBag`);
      button.forEach((button) => {
        button.addEventListener(`click`, function (e) {
          const clicked = e.target;
          const kupi = clicked.closest(`.kupi`);
          const cijena2 = kupi.querySelector(`span`).innerText;
          const cijena = cijena2.split(` `)[0];
          const parent = kupi.closest(`.movie`);
          const imeFilma = parent.querySelector(`.movie-info h3`).innerText;
          const imgSrc = parent.querySelector(`img`).src;

          const singleItem = `
          <div class="single-item">
             <span class="material-symbols-outlined deleteItem"> close </span>
               <img src=${imgSrc} alt="aaa" class="smallPic" />
                   <div class="opis">
                       <h2>${imeFilma}</h2>
                    </div>
                   <div class="kolicina">
                      <button class="plus">+</button>
                     <input type="text" value="1" max="3" min="1" class="input"/>
                     <button class="minus">-</button>
                   </div>
               <div class="single-total" data-value="${cijena}">${cijena} KN</div>
            </div>
          `;

          shoopingCart.innerHTML += singleItem;

          const basketTotal = `
          <div class="totalKosara vidljivo">
        <div class="potvrdi">
          <p class="sub">Subtotal</p>
          <p class="price">675 KN</p>
        </div>
        <div class="text">
          <p>Shipping, taxes and discounts calculated at checkout.</p>
        </div>
        <div class="blue"><button>Checkout</button></div>
      </div>
          `;

          //shoopingCart.innerHTML += basketTotal;

          const removeElement = function () {
            const nodes = document.querySelectorAll(`.single-item`);
            let lastNode = nodes[nodes.length - 1];
            if (lastNode) {
              lastNode.insertAdjacentHTML(`afterend`, basketTotal);
            }
          };

          removeElement();

          //OBRISI ITEM
          const deleteItem = document.querySelectorAll(`.deleteItem`);
          deleteItem.forEach((btn) => {
            btn.addEventListener(`click`, function (e) {
              const mainEl = e.target.closest(`.single-item`);
              mainEl.parentNode.removeChild(mainEl);
              button.disabled = false;
            });
          });

          //add more movies btn
          const plusBtn = document.querySelectorAll(`.plus`);
          const minusBtn = document.querySelectorAll(`.minus`);

          plusBtn.forEach((btn) => {
            btn.addEventListener(`click`, function (e) {
              let plus = e.target;
              let parent = plus.closest(`.kolicina`);
              let input = parent.querySelector(`.input`);
              let singleEl = parent.closest(`.single-item`);
              let singleTotal = singleEl.querySelector(`.single-total`);

              input.value++;
              if (input.value > 3) input.value = 3;
              singleTotal.innerText = `${
                singleTotal.dataset.value * input.value
              } KN`;
            });
          });

          minusBtn.forEach((btn) => {
            btn.addEventListener(`click`, function (e) {
              let plus = e.target;
              let parent = plus.closest(`.kolicina`);
              let input = parent.querySelector(`.input`);
              let singleEl = parent.closest(`.single-item`);
              let singleTotal = singleEl.querySelector(`.single-total`);

              input.value--;
              console.log(input.innerText);
              if (input.value < 1) input.value = 1;
              singleTotal.innerText = `${
                singleTotal.dataset.value * input.value
              } KN`;
            });
          });
        });
      });
    });
  })
  .catch((err) => console.error(err));


------------------------------------------------------- html ----------------------------------------------

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Filmovizija</title>
  </head>
  <body>
    <h1>Filmovizija</h1>
    <div class="prozor"></div>
    <h2>Shooping bag</h2>
    <div class="shooping-cart"></div>

    <script src="script.js"></script>
  </body>
</html>

--------------------------------------------------- CSS -----------------------------------------------
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #22254b;
  font-family: "Poppins", sans-serif;
}

h1 {
  text-align: center;
  color: #eee;
  font-family: inherit;
  margin-top: 30px;
  margin-bottom: 30px;
}

.prozor {
  display: flex;
  flex-wrap: wrap;
}

.movie {
  width: 300px;
  border-radius: 4px;
  box-shadow: 0 4px 5px rgba(0, 0, 0, 0.3);
  background-color: #373b69;
  margin: 25px;
}

.movie-info {
  color: #eee;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  letter-spacing: 1px;
  align-items: center;
}

.movie img {
  width: 100%;
  border-bottom: 1px solid white;
  height: 450px;
}

.movie-info h3 {
  font-weight: 300;
  margin: 0;
}

.movie-info span {
  font-weight: 400;
  border-radius: 3px;
  background-color: #22254b;
  padding: 3px 7px;
}

.movie .kupi {
  color: #eee;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  padding-bottom: 15px;
  letter-spacing: 1px;
  align-items: center;
}

.movie .kupi button {
  padding: 2px 8px;
  font-size: 14px;
  font-weight: 500;
}

.movie .kupi span {
  font-size: 18px;
  font-weight: 500;
}

/* ----------------------------------- SHOOPING CART ------------------------------------------------ */

.shooping-cart {
  border-top: 2px solid rgb(214, 214, 214);
  width: 1000px;
  height: 500px;
  margin-left: 25px;
}

h2 {
  color: whitesmoke;
  text-transform: uppercase;
  font-size: 20px;
  font-weight: 300;
  margin-bottom: 20px;
  margin-left: 25px;
}

.shooping-cart .single-item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 2px dotted grey;
}

.shooping-cart .single-item span {
  background-color: rgb(255, 255, 255);
  margin-left: 20px;
  border-radius: 50%;
  color: black;
}

.smallPic {
  height: 70px;
  width: 70px;
  border: 1px solid grey;
}

.shooping-cart .single-item .opis {
  align-items: center;
  display: flex;
  flex-direction: column;
  color: white;
  font-family: inherit;
}

.shooping-cart .single-item .opis h2 {
  font-weight: 300;
  margin-bottom: 5px;
}

.shooping-cart .single-item .opis h3 {
  font-size: 14px;
  font-weight: bold;
  color: antiquewhite;
  text-transform: uppercase;
}

.shooping-cart .single-item .kolicina input {
  width: 30px;
  text-align: center;
}

.shooping-cart .single-item .kolicina button {
  padding: 2px 6px;
  background-color: whitesmoke;
  border: 0;
}

.single-total {
  color: white;
  margin-right: 20px;
}

/* ----------------------------------- SHOOPING CART TOTAL ALL ------------------------------------------------ */

.totalKosara {
  float: right;
  display: flex;
  flex-direction: column;
  width: 350px;
  height: 160px;
  margin-top: 15px;
}

.potvrdi {
  display: flex;
  width: 100%;
  margin: 20px 0;
  justify-content: space-between;
  text-align: center;
}

.potvrdi .sub,
.price {
  color: #eee;
  font-weight: bold;
  padding: 5px;
}

.text {
  color: white;
  font-size: 14px;
  text-align: center;
}

.blue {
  width: 100%;
  align-items: center;
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.blue button {
  width: 100%;
  border-radius: 2px;
  border: 0;
  padding: 10px;
  background-color: #0b1050;
  color: #eee;
  font-family: inherit;
  border: 1px solid grey;
}





Hi,
use the appendChild() method:

  1. First create a new div (the outer div of the element you want to append) with document.createElement.
  2. Add the class to that element (yourElement.classList.add()).
  3. Then set the innerHTML of that newly created element as you already did with the parent, just without the outer div.
  4. Then append that newly created element to main.

I have done this.

const outerDiv = document.createElement(div);
outerDiv.classList.add(checkoutButton);

I am not sure what you mean on steps 3. and 4.

html

<div id="parent">
  <div class="child1">
    <p>Hello</p>
  </div>
</div>

JavaScript

const parent = document.getElementById('parent');
const newChild = document.createElement('div');
newChild.classList.add('child2');
newChild.innerHTML = '<p>world!</p>'
parent.appendChild(newChild);

Result

<div id="parent">
  <div class="child1">
    <p>Hello</p>
  </div>
  <div class="child2">
    <p>world!</p>
  </div>
</div>

Please always format your code. Otherwise characters like apostrophs aren’t displayed.

1 Like

Okay, I undestrand what you have done here, but still can’t make it work in my project.

I don’t see the problem, actually. If I test your code and click ‘kupi film’, the movie is added to the end of the shopping list exactly once.

I am not talking about movie. I am talking about this. First look at imgur link I provided.
You see that I added 2 movies. Under the eachj movie I have html content which consists of this:

Subtotal 675kn
Shiiping, taxes and discounts…
Checkout button.

I only want to add this html element on the last movie, and when I add few movies then total price of all movies will be there.

code for this html element is in js file, and here it is:

const basketTotal = `
          <div class="totalKosara vidljivo">
        <div class="potvrdi">
          <p class="sub">Subtotal</p>
          <p class="price">675 KN</p>
        </div>
        <div class="text">
          <p>Shipping, taxes and discounts calculated at checkout.</p>
        </div>
        <div class="blue"><button>Checkout</button></div>
      </div>
          `;

So again, I only want to display it on the last movie, no matter if there is one, two or 10 movies.

Yep, I see what you mean now. Wasn’t aware that there is a link on the image. But I’m not motivated to spend more time on this. Just this much: You need to address the last element inside the parent container with its index elements[elements.length].
Maybe s/o else likes to go into details.