Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chèn node làm child trước child đã có trong JavaScript

JavaScript cung cấp insertBefore() chèn node làm child trước child khác. Nếu có 2 list, có thể sắp xếp lại element giữa chúng.

Cú pháp

parentNode.insertBefore(newNode, existingNode);

Ví dụ 1: Chèn trước child thứ 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[1]); </script> </body> </html>

Kết quả

Tesla Google Solarcity Drupal

Ví dụ 2: Chèn trước child đầu tiên

<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>

Kết quả

Google Tesla Solarcity Drupal

Lưu ý: firstChild có thể là text node. Nên dùng firstElementChild. Node được di chuyển (không copy) - nó bị xóa khỏi parent cũ.