首页 > 解决方案 > 添加新的

  • 元素成
  • 问题描述

    这是我的 html 代码

    function addChildren() {
      var el = document.getElementById('one');
    
      //Create new node and textNode
      var newEl = document.createElement('li');
      var newText = document.createTextNode('New Node Text');
    
      //Append as child Node
      newEl.appendChild(newText);
      newEl.setAttribute('class', 'hot');
    
      //Append as child Node to the last of list
      el.appendChild(newEl);
    
      //Append as child node to the beginning of list
      el.insertBefore(newEl, el.firstChild);
    }
    
    document.querySelector('#add').
      addEventListener('click', addChildren);
    <ul id='one'>
      <li class='hot'>Hello</li>
      <li class='hot'>World</li>
      <li class='hot'>This</li>
      <li class='hot'>Is</li>
      <li class='hot'>Ben!</li>
    </ul>
    
    <button id="add">Add</button>

    为什么脚本只执行 1 次插入新元素,尽管我放入了 2 次(insertBefore 和 appendChild)?

    当我尝试添加多个 'appendChild()' 方法时,只添加了 1 个新元素,这是为什么呢?

    标签: javascripthtml

    解决方案


    您试图在两个地方添加相同的节点,所以最后一个获胜。该节点实际上被添加到末尾,但立即移动到开头。

    您可以克隆节点,并将克隆插入到开头:

    function addChildren() {
      var el = document.getElementById('one');
    
      //Create new node and textNode
      var newEl = document.createElement('li');
      var newText = document.createTextNode('New Node Text');
    
      //Append as child Node
      newEl.appendChild(newText);
      newEl.setAttribute('class', 'hot');
    
      //Append as child Node to the last of list
      el.appendChild(newEl);
    
      // create a clone of the node
      var clone = newEl.cloneNode(true);
      
      //Append the clone as child node to the beginning of list
      el.insertBefore(clone, el.firstChild);
    }
    
    document.querySelector('#add').
      addEventListener('click', addChildren);
    <ul id='one'>
      <li class='hot'>Hello</li>
      <li class='hot'>World</li>
      <li class='hot'>This</li>
      <li class='hot'>Is</li>
      <li class='hot'>Ben!</li>
    </ul>
    
    <button id="add">Add</button>


    推荐阅读