首页 > 解决方案 > how to append the button to each

  • 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>

    标签: javascript

    解决方案


    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>


    推荐阅读