Phương thức insertBefore () của XML DOM
❮ Đối tượng nút
Thí dụ
Đoạn mã sau tải " books.xml ", tạo một nút <book> mới và chèn nó trước nút <book> cuối cùng:
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;
}
Đầu ra của đoạn mã trên sẽ là:
Book elements before: 4
Book elements after: 5
Định nghĩa và Cách sử dụng
Phương thức insertBefore () chèn một nút con mới trước một nút con được chỉ định của nút hiện tại.
Lưu ý: Nếu đứa trẻ mới đã ở trên cây, nó sẽ được gỡ bỏ trước tiên.
Hỗ trợ trình duyệt
Phương thức insertBefore () được hỗ trợ trong tất cả các trình duyệt chính.
Cú pháp
nodeObject.insertBefore(newchild,existingnode)
Thông số
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 |
Giá trị trả lại
Type | Description |
---|---|
Node object | The inserted node |
Chi tiết kỹ thuật
Phiên bản DOM | Đối tượng nút cấp độ lõi 1. Đã sửa đổi trong DOM cấp 3 |
---|
❮ Đối tượng nút