NotFoundError:事件侦听器中insertBefore上的DOM异常8

时间:2015-07-08 12:46:56

标签: javascript dom

我有以下代码:

HTML:

<div id="tree">
  <ul class="root">
    <li class="add">+</li>
  </ul>
</div>

JavaScript的:

window.onload = () => {
  let root = document.getElementsByClassName("root")[0];
  root.addEventListener("click", (e) => {
    if (e.target.classList.contains("add")) addNode(e);
    return false;
  }, false);

  function addNode(e) {
    let item = document.createElement("li");
    item.innerHTML = "new";
    e.target.parentNode.insertBefore(e.target, item);
  }
};

当我点击li时,我在insertBefore的行上得到错误NotFoundError: DOM Exception 8: An attempt was made to reference a Node in a context where it does not exist.。我已经检查过DevTools,一切似乎都是正常的节点,我不知道它为什么不起作用。

1 个答案:

答案 0 :(得分:1)

参数的顺序不正确。必须首先传递新节点:

e.target.parentNode.insertBefore(item, e.target);

See the MDN documentation