HTML DOM แทรกก่อน ()เมธอด
ตัวอย่าง
แทรกองค์ประกอบ <li> ใหม่ก่อนองค์ประกอบลูกคนแรกขององค์ประกอบ <ul>:
var newItem = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
newItem.appendChild(textnode); // Append the text to <li>
var list = document.getElementById("myList"); // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]); // Insert <li> before the first child of <ul>
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
เมธอด insertBefore() จะแทรกโหนดเป็นโหนดย่อย ก่อนรายการย่อยที่มีอยู่ ซึ่งคุณระบุ
เคล็ดลับ:หากคุณต้องการสร้างรายการใหม่โดยใช้ข้อความ อย่าลืมสร้างข้อความเป็นโหนดข้อความซึ่งคุณผนวกเข้ากับองค์ประกอบ <li> จากนั้นแทรก <li> ลงในรายการ
คุณยังสามารถใช้เมธอด insertBefore เพื่อแทรก/ย้ายองค์ประกอบที่มีอยู่ (ดู "ตัวอย่างเพิ่มเติม")
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่รองรับวิธีการนี้อย่างเต็มที่
Method | |||||
---|---|---|---|---|---|
insertBefore() | Yes | Yes | Yes | Yes | Yes |
ไวยากรณ์
node.insertBefore(newnode, existingnode)
ค่าพารามิเตอร์
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object you want to insert |
existingnode | Node object | Required. The child node you want to insert the new node before. If set to
null , the insertBefore method will insert the newnode at the end |
รายละเอียดทางเทคนิค
คืนมูลค่า: | Node Object แทนโหนดที่แทรก |
---|---|
เวอร์ชัน DOM | วัตถุโหนดหลักระดับ 1 |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ย้าย <li> องค์ประกอบจากรายการหนึ่งไปยังอีกรายการหนึ่ง:
var node = document.getElementById("myList2").lastChild;
var list = document.getElementById("myList1");
list.insertBefore(node, list.childNodes[0]);