pranshul pandey
pranshul pandey

Reputation: 43

how to append the button to each <li> tag in javascript using forEach loop

I want to append the button tag to each of the 6 li tags using a forEach loop but after running the below code I am only getting a button tag on the 6th (last) li tag. Please help and let me what I am doing wrong.

var button = document.createElement('button');
button.appendChild(document.createTextNode('delete'));
var spam = document.createElement('spam');
var li = document.querySelectorAll('li');

li.forEach(function(i) {
  i.appendChild(button);
});
<body>
  <h1>Shopping List</h1>
  <p id="first">Get it done today</p>
  <input id="userinput" type="text" placeholder="enter items">
  <button id="enter" width='50px'>Enter</button>
  <ul>
    <li class="bold red" random="23">Notebook</li>
    <li>Jello</li>
    <li>Spinach</li>
    <li>Rice</li>
    <li>Birthday Cake</li>
    <li>Candles</li>
  </ul>
</body>

Upvotes: 1

Views: 1704

Answers (2)

rez shahr
rez shahr

Reputation: 49

as @Shubh said you need to move the createElement inside the foreach loop. and create a new button element each time and append it to the li elements. because the variable button that you created at the beginnig is refering to the created element. each iteration you are just assigning it to another li node. so:

li.forEach(function(item){ 
      var button=document.createElement('button');
  button.appendChild(document.createTextNode('delete'));
  item.appendChild(button);
   });

Upvotes: 0

Shubham Dixit
Shubham Dixit

Reputation: 1

Just move document.createElement('button')in forEach Loop of yours

var spam = document.createElement('spam');
var li = document.querySelectorAll('li');

li.forEach(function(i) {
  var button = document.createElement('button');
  button.appendChild(document.createTextNode('delete'));
  i.appendChild(button);
});
<body>
  <h1>Shopping List</h1>
  <p id="first">Get it done today</p>
  <input id="userinput" type="text" placeholder="enter items">
  <button id="enter" width='50px'>Enter</button>
  <ul>
    <li class="bold red" random="23">Notebook</li>
    <li>Jello</li>
    <li>Spinach</li>
    <li>Rice</li>
    <li>Birthday Cake</li>
    <li>Candles</li>
  </ul>

</body>

Upvotes: 4

Related Questions