XML DOM แทรกก่อน ()เมธอด
❮ วัตถุโหนด
ตัวอย่าง
โค้ดย่อยต่อไปนี้โหลด " books.xml " สร้างโหนด <book> ใหม่และแทรกก่อนโหนด <book> สุดท้าย:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var newNode =
xmlDoc.createElement("book");
var x =
xmlDoc.documentElement;
var y =
xmlDoc.getElementsByTagName("book");
document.getElementById("demo").innerHTML =
"Book
elements before: " + y.length + "<br>";
x.insertBefore(newNode, y[3]);
document.getElementById("demo").innerHTML
+=
"Book elements after: " + y.length;
}
ผลลัพธ์ของโค้ดด้านบนจะเป็น:
Book elements before: 4
Book elements after: 5
ความหมายและการใช้งาน
เมธอด insertBefore() จะแทรกโหนดย่อยใหม่ก่อนโหนดย่อยที่ระบุของโหนดปัจจุบัน
หมายเหตุ:หากเด็กใหม่อยู่ในทรีแล้ว จะถูกลบออกก่อน
รองรับเบราว์เซอร์
รองรับเมธอด insertBefore() ในเบราว์เซอร์หลักทั้งหมด
ไวยากรณ์
nodeObject.insertBefore(newchild,existingnode)
พารามิเตอร์
Parameter | Type | Description |
---|---|---|
newchild | Node object | Required. The new child node to insert |
existingnode | Node object | Required. The node to insert the new child node before. If existingnode is null, insert newchild at the end of the list of children |
คืนมูลค่า
Type | Description |
---|---|
Node object | The inserted node |
รายละเอียดทางเทคนิค
เวอร์ชัน DOM | วัตถุโหนดหลักระดับ 1 แก้ไขใน DOM ระดับ 3 |
---|
❮ วัตถุโหนด