在<ul>问题中添加新的<li>元素

时间:2019-11-16 08:19:02

标签: javascript html

这是我的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>

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

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

1 个答案:

答案 0 :(得分:3)

您试图在两个位置添加相同的节点,所以最后一个赢了。该节点实际上已添加到末尾,但立即移到了开始。

您可以clone节点,并将克隆插入到起始位置:

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>