在JavaScript中有insertBefore(),但如何在不使用jQuery或其他库的情况下在另一个元素之后插入一个元素?


当前回答

让我们来处理所有的情况

 function insertAfter(newNode, referenceNode) {
        if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == '#text')
            referenceNode = referenceNode.nextSibling;

        if(!referenceNode)
            document.body.appendChild(newNode);
        else if(!referenceNode.nextSibling)
            document.body.appendChild(newNode);
        else            
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);            
    }

其他回答

insertAfter的健壮实现。

// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
  function isNode(node) {
    return node instanceof Node;
  }

  if(arguments.length < 2){
    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
  }

  if(isNode(newNode)){
    if(referenceNode === null || referenceNode === undefined){
      return this.insertBefore(newNode, referenceNode);
    }

    if(isNode(referenceNode)){
      return this.insertBefore(newNode, referenceNode.nextSibling);
    }

    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
  }

  throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};

这是使用普通javascript在另一个元素之后添加一个元素的最简单方法

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

参考: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

方法节点。After (doc)在另一个节点之后插入一个节点。

对于两个DOM节点node1和node2,

node1.after(node2)在node1之后插入node2。

这个方法在旧的浏览器中是不可用的,所以通常需要填充。

我使用以下命令在选择的末尾插入选项。通过传递null作为第二个参数。我不确定这是否是一个异常的“选择”元素,因为我从来没有尝试过其他任何东西,但如果有人来这里寻找这个可能会有所帮助。在IE上也能工作(令人惊讶)。:)

            var x = document.getElementById("SELECT_LIST");
            var boption = document.createElement("option");
            boption.text = "SOME TEXT";
            boption.value = "SOME VALUE";
            x.insertBefore(boption, null);

让我们来处理所有的情况

 function insertAfter(newNode, referenceNode) {
        if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == '#text')
            referenceNode = referenceNode.nextSibling;

        if(!referenceNode)
            document.body.appendChild(newNode);
        else if(!referenceNode.nextSibling)
            document.body.appendChild(newNode);
        else            
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);            
    }