Home > Back-end >  How to make the first item in the list give room for the second item and so on?
How to make the first item in the list give room for the second item and so on?

Time:06-18

I created a button that when clicked creates an item on the list div. In the list div 'Total:' is hard coded. I want the total to go down whenever an item is created so that the item takes its place and the total can be shown at the bottom. But the problem total will remain in its place, and the item will be created beneath it. How can I change that from happening?

Here's the code(trial):

const btn = document.querySelector(".btn");
const itemList = document.querySelector(".item-list");

btn.addEventListener('click', function(e) {
  const para = document.createElement('div');
  para.classList.add('item-list');
  para.innerHTML = `<p >Potato Chips</p>`
  itemList.appendChild(para);
})
.list-container {
  height: 500px;
  width: 300px;
  background-color: cadetblue;
}

header {
  background-color: burlywood;
  border-style: groove;
}

.btn {
  margin-bottom: 20px;
}
<div >
  <header>
    <h4>List Time</h4>
    <button >click</button>
  </header>
  <div >
    <div>
      <p>Total: </p>
    </div>
  </div>
</div>

CodePudding user response:

You can use insertBefore instead of appendChild (Or prepend as suggested by Titus in the comments). I'll use insertBefore in my example.

const btn = document.querySelector(".btn");
const itemList = document.querySelector(".item-list");
const totalEl = document.getElementById('total'); // added id on the element I want to insert items before
btn.addEventListener('click', function(e) {
  const para = document.createElement('div');
  para.classList.add('item-list');
  para.innerHTML = `<p >Potato Chips</p>`
  itemList.insertBefore(para, totalEl);
})
.list-container {
  height: 500px;
  width: 300px;
  background-color: cadetblue;
}

header {
  background-color: burlywood;
  border-style: groove;
}

.btn {
  margin-bottom: 20px;
}
<div >
  <header>
    <h4>List Time</h4>
    <button >click</button>
  </header>
  <div >
    <div id="total">
      <p>Total: </p>
    </div>
  </div>
</div>

CodePudding user response:

Use "prepend" instead of "appendChild", as "prepend" will insert before the element, but append will insert after.

const btn = document.querySelector(".btn");
const itemList = document.querySelector(".item-list");

btn.addEventListener('click', function(e) {
  const para = document.createElement('div');
  para.classList.add('item-list');
  para.innerHTML = `<p >Potato Chips</p>`
  itemList.prepend(para);
})
.list-container {
  height: 500px;
  width: 300px;
  background-color: cadetblue;
}

header {
  background-color: burlywood;
  border-style: groove;
}

.btn {
  margin-bottom: 20px;
}
<div >
  <header>
    <h4>List Time</h4>
    <button >click</button>
  </header>
  <div >
    <div>
      <p>Total: </p>
    </div>
  </div>
</div>

  • Related