dom appendchild用法 - 如何在不使用库的情况下在JavaScript的另一个元素之后插入元素?




原生js append用法 (14)

JavaScript中有insertBefore() ,但是如何不使用jQuery或其他库的情况下插入元素?


Answers

步骤1.准备元素:

var element = document.getElementById('ElementToAppendAfter');
var newElement = document.createElement('div');
var elementParent = element.parentNode;

第2步。追加后:

elementParent.insertBefore(newElement, element.nextSibling);


伟大的Dustin Diaz在一篇文章中写道:分析它并在第一个答案中提供代码,并稍作修改:

function insertAfter(parent, node, referenceNode) {

  parent.insertBefore(node, referenceNode.nextSibling);

}

http://www.dustindiaz.com/top-ten-javascript


理想情况下, insertAfter应该与insertBefore类似。 下面的代码将执行以下操作:

  • 如果没有孩子,则添加新的Node
  • 如果没有参考Node ,则添加新Node
  • 如果参考Node之后没有Node ,则添加新Node
  • 如果参考Node有兄弟Node则在该兄弟Node之前插入新的Node
  • 返回新Node

扩展Node

Node.prototype.insertAfter = function(node, referenceNode) {

    if (node)
        this.insertBefore(node, referenceNode && referenceNode.nextSibling);

    return node;
};

一个常见的例子

node.parentNode.insertAfter(newNode, node);

看代码运行

// First extend
Node.prototype.insertAfter = function(node, referenceNode) {
    
    if (node)
        this.insertBefore(node, referenceNode && referenceNode.nextSibling);

    return node;
};

var referenceNode,
    newNode;

newNode = document.createElement('li')
newNode.innerText = 'First new item';
newNode.style.color = '#FF0000';

document.getElementById('no-children').insertAfter(newNode);

newNode = document.createElement('li');
newNode.innerText = 'Second new item';
newNode.style.color = '#FF0000';

document.getElementById('no-reference-node').insertAfter(newNode);

referenceNode = document.getElementById('no-sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Third new item';
newNode.style.color = '#FF0000';

referenceNode.parentNode.insertAfter(newNode, referenceNode);

referenceNode = document.getElementById('sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Fourth new item';
newNode.style.color = '#FF0000';

referenceNode.parentNode.insertAfter(newNode, referenceNode);
<h5>No children</h5>
<ul id="no-children"></ul>

<h5>No reference node</h5>
<ul id="no-reference-node">
  <li>First item</li>
</ul>

<h5>No sibling after</h5>
<ul>
  <li id="no-sibling-after">First item</li>
</ul>

<h5>Sibling after</h5>
<ul>
  <li id="sibling-after">First item</li>
  <li>Third item</li>
</ul>


 <!DOCTYPE html>
 <html lang="ca">
 <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function createDiv(){
            var newDiv = document.createElement("div");
            var txt = document.createTextNode("I'm the second div");
            newDiv.appendChild(txt);
            var x = document.getElementsByTagName("BODY")[0];
            x.insertBefore(newDiv, third);
        }
    </script>
</head>
<body>
    <div class="first">
        <p>
            I'm the first div
        </p>
    </div>
    <div id="third">
        <p>
            I'm the third div
        </p>
    </div>
    <button type= " button " name= " button " onclick = " createDiv() " >
        Create the second Div
    </button>
</body>
</html>

node1.after(node2)生成<node1/><node2/>

其中node1和node2是DOM节点。

.after()是一种非常新的方法[1] ,因此浏览器支持可能是一个问题。


让我们处理所有情况

 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);            
    }

直截了当的JavaScript将是以下内容:

追加前:

element.parentNode.insertBefore(newElement, element);

追加后:

element.parentNode.insertBefore(newElement, element.nextSibling);

但是,抛弃一些原型以方便使用

通过构建以下原型,您将能够直接从新创建的元素中调用这些函数。

  • newElement.appendBefore(element);

  • newElement.appendAfter(element);

.appendBefore(元素)原型

Element.prototype.appendBefore = function (element) {
  element.parentNode.insertBefore(this, element);
},false;

.appendAfter(element)原型

Element.prototype.appendAfter = function (element) {
  element.parentNode.insertBefore(this, element.nextSibling);
},false;

而且,要查看它的全部内容,请运行以下代码片段

/* Adds Element BEFORE NeighborElement */
Element.prototype.appendBefore = function(element) {
  element.parentNode.insertBefore(this, element);
}, false;

/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function(element) {
  element.parentNode.insertBefore(this, element.nextSibling);
}, false;


/* Typical Creation and Setup A New Orphaned Element Object */
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';


/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */
NewElement.appendAfter(document.getElementById('Neighbor2'));
div {
  text-align: center;
}
#Neighborhood {
  color: brown;
}
#NewElement {
  color: green;
}
<div id="Neighborhood">
  <div id="Neighbor1">Neighbor 1</div>
  <div id="Neighbor2">Neighbor 2</div>
  <div id="Neighbor3">Neighbor 3</div>
</div>

在JSFiddle上运行它


虽然insertBefore() (请参阅insertBefore )非常好,并在此处引用了大多数答案。 为了增加灵活性,并且更加明确一点,您可以使用:

insertAdjacentElement() (请参阅developer.mozilla.org/en-US/docs/Web/API/Element/… )这使您可以引用任何元素,并将要移动的元素完全插入到您想要的位置:

<!-- refElem.insertAdjacentElement('beforebegin', moveMeElem); -->
<p>
<!-- refElem.insertAdjacentElement('afterbegin', moveMeElem); -->
... content ...
<!-- refElem.insertAdjacentElement('beforeend', moveMeElem); -->
</p>
<!-- refElem.insertAdjacentElement('afterend', moveMeElem); -->

其他人要考虑类似的用例: insertAdjacentHTML()insertAdjacentText()

参考文献:

developer.mozilla.org/en-US/docs/Web/API/Element/… developer.mozilla.org/en-US/docs/Web/API/Element/… https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText


或者你可以简单地做:

referenceNode.parentNode.insertBefore( newNode, referenceNode )
referenceNode.parentNode.insertBefore( referenceNode, newNode )

一个强大的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'."));

};


快速谷歌搜索显示此脚本

// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
    // target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode;

    // if the parents lastchild is the targetElement...
    if (parent.lastChild == targetElement) {
        // add the newElement after the target element.
        parent.appendChild(newElement);
    } else {
        // else the target has siblings, insert the new element between the target and it's next sibling.
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

此代码用于在最后一个现有子项之后插入一个链接项目inlining一个小型css文件

var raf, cb=function(){
    //create newnode
    var link=document.createElement('link');
    link.rel='stylesheet';link.type='text/css';link.href='css/style.css';

    //insert after the lastnode
    var nodes=document.getElementsByTagName('link'); //existing nodes
    var lastnode=document.getElementsByTagName('link')[nodes.length-1]; 
    lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
};

//check before insert
try {
    raf=requestAnimationFrame||
        mozRequestAnimationFrame||
        webkitRequestAnimationFrame||
        msRequestAnimationFrame;
}
catch(err){
    raf=false;
}

if (raf)raf(cb); else window.addEventListener('load',cb);

您可以通过执行以下Array.insert来实现Array.insert方法:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

然后你就可以使用它:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]




javascript dom insert append