จาวาสคริปต์ ได้ให้ insertBefore() วิธีการแทรกโหนดเป็นลูกก่อนลูกอื่น หากมี 2 รายการ เราสามารถสับเปลี่ยนองค์ประกอบระหว่างกันตามความต้องการของเราโดยใช้วิธีการ insertBefore() .
ไวยากรณ์
node.insertBefore(newnode, existingnode);
ตัวอย่าง-1
ในตัวอย่างต่อไปนี้ มีสองรายการและตามข้อกำหนดของเรา รายการจะถูกสับเปลี่ยนโดยใช้ insertBefore() วิธีการ ในการเข้าถึง หลายองค์ประกอบในรายการที่เราสามารถใช้ดัชนีได้
<html>
<body>
<ul id="List1"> <li>Tesla </li><li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[1]);
</script>
</body>
</html> ผลลัพธ์
Tesla Google Solarcity Drupal
ตัวอย่าง-2
<html>
<body>
<ul id="List1"> <li>Tesla </li> <li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[0]);
</script>
</body>
</html> ผลลัพธ์
Google Tesla Solarcity Drupal