1

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>

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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);
   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.