Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แทรก Node เป็น Child ก่อน Child ที่มีอยู่ใน JavaScript

JavaScript มีเมธอด insertBefore() แทรก Node เป็น Child ก่อน Child อื่น ถ้ามี 2 Lists สามารถสลับ Elements ระหว่างกันได้ตามต้องการด้วย insertBefore()

Syntax

node.insertBefore(newnode, existingnode);

ตัวอย่างที่ 1

ในตัวอย่างนี้ มี 2 Lists และสลับ Elements ระหว่างกันตามต้องการด้วย insertBefore() เข้าถึง Multiple Elements ใน List ได้ด้วย Indexes

<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