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

Phương thức insertBefore() trong HTML DOM

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ả
newNodeLà nút con mới được tạo sẽ được chèn vào đầu
existingNodeLà 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':

Phương thức insertBefore() trong HTML DOM

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

Phương thức insertBefore() trong HTML DOM