如何在不使用庫的情況下在JavaScript中的另一個元素之後插入元素?

本文翻譯自:How to insert an element after another element in JavaScript without using a library?

在JavaScript中有insertBefore() ,但是如何不使用jQuery或其他庫的情況下另一個元素之後插入元素?


#1樓

參考:https://stackoom.com/question/K72C/如何在不使用庫的情況下在JavaScript中的另一個元素之後插入元素


#2樓

insertAdjacentHTML + outerHTML insertAdjacentHTML + outerHTML

elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)

Upsides: 上升空間:

  • DRYer: you don't have to store the before node in a variable and use it twice. DRYer:您不必將before節點存儲在變量中並使用它兩次。 If you rename the variable, on less occurrence to modify. 如果重命名變量,則在較少的情況下進行修改。
  • golfs better than the insertBefore (break even if the existing node variable name is 3 chars long) 高爾夫球比insertBefore更好(即使現有的節點變量名稱是3個字符長也會中斷)

Downsides: 缺點:

  • lower browser support since newer: https://caniuse.com/#feat=insert-adjacent 更新瀏覽器支持: https//caniuse.com/#feat=insert-adjacent
  • will lose properties of the element such as events because outerHTML converts the element to a string. 將丟失元素的屬性,例如events,因爲outerHTML將元素轉換爲字符串。 We need it because insertAdjacentHTML adds content from strings rather than elements. 我們需要它,因爲insertAdjacentHTML從字符串而不是元素添加內容。

#3樓

insertBefore() method is used like parentNode.insertBefore() . insertBefore()方法與parentNode.insertBefore()一樣使用。 So to imitate this and make a method parentNode.insertAfter() we can write the following code. 因此,爲了模仿這個並創建一個方法parentNode.insertAfter()我們可以編寫以下代碼。

JavaScript JavaScript的

Node.prototype.insertAfter = function(newNode, referenceNode) {
    return referenceNode.parentNode.insertBefore(
        newNode, referenceNode.nextSibling); // based on karim79's solution
};

// getting required handles
var refElem = document.getElementById("pTwo");
var parent = refElem.parentNode;

// creating <p>paragraph three</p>
var txt = document.createTextNode("paragraph three");
var paragraph = document.createElement("p");
paragraph.appendChild(txt);

// now we can call it the same way as insertBefore()
parent.insertAfter(paragraph, refElem);

HTML HTML

<div id="divOne">
    <p id="pOne">paragraph one</p>
    <p id="pTwo">paragraph two</p>
</div>

Note, that extending the DOM might not be the right solution for You as stated in this article . 請注意,延長DOM可能不適合你的解決方案中所述這篇文章

Hovewer, this article was written in 2010 and things might be different now. Hovewer,這篇文章寫於2010年,現在情況可能有所不同。 So decide on Your own. 所以決定你自己。

JavaScript DOM insertAfter() method @ jsfiddle.net JavaScript DOM insertAfter()方法@ jsfiddle.net


#4樓

This code is work to insert a link item right after the last existing child to inlining a small css file 此代碼用於在最後一個現有子項之後插入鏈接項以內聯小型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);

#5樓

Or you can simply do: 或者你可以簡單地做:

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

#6樓

Straightforward JavaScript Would Be the Following: 直截了當的JavaScript將是以下:

Append Before: 追加之前:

element.parentNode.insertBefore(newElement, element);

Append After: 追加後:

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

But, Toss Some Prototypes In There For Ease of Use 但是,在那裏折騰一些原型以便於使用

By building the following prototypes, you will be able to call these function directly from newly created elements. 通過構建以下原型,您將能夠直接從新創建的元素中調用這些函數。

  • newElement.appendBefore(element);

  • newElement.appendAfter(element);

.appendBefore(element) Prototype .appendBefore(element)原型

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

.appendAfter(element) Prototype .appendAfter(element)原型

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

And, To See It All In Action, Run the Following Code Snippet 並且,要查看所有操作,請運行以下代碼段

 /* 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> 

Run it on JSFiddle 在JSFiddle上運行它

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章