Phương thức insertBefore() trong HTML DOM chèn một nút mới trước một nút con đã tồn tại.
Cú pháp
Gọi insertBefore() với tham số newNode và existingNode:
node.insertBefore(newNode, existingNode)
Ở đây, tham số có thể là:
Tham số
| Tham số | Mô tả |
|---|---|
| newNode | Là nút con mới được tạo sẽ được chèn vào đầu |
| existingNode | Là nút đã tồn tại |
Ví dụ
Ví dụ minh họa phương thức insertBefore():
<!DOCTYPE html> <html> <head> <title>insertBefore()</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } ol { width:30%; margin: 0 auto; } </style> </head> <body> <form> <fieldset> <legend>insertBefore()</legend> <h1>Cách pha trà</h1> <h3>Các bước:</h3> <ol id="stepList"> <li>Cho túi trà</li> <li>Cho đường</li> <li>Cho sữa</li> </ol> <input type="button" onclick="addStep()" value="Thêm"> </fieldset> </form> <script> function addStep() { var newIngredient = document.createElement("LI"); var textnode = document.createTextNode("Đun nước sôi"); newIngredient.appendChild(textnode); var stepList = document.getElementById("stepList"); stepList.insertBefore(newIngredient, stepList.childNodes[0]); } </script> </body> </html>
Kết quả
Trước khi nhấn nút 'Thêm':

Sau khi nhấn nút 'Thêm':
