Phương thức HTML DOM insertBefore () chèn một nút mới trước một nút con đã tồn tại.
Cú pháp
Sau đây là cú pháp -
Gọi insertBefore () với các tham số của positionString và text
node.insertBefore(newNode, existingNode)
Đây, thông số có thể như sau -
Tham số
| tham số | Mô tả |
|---|---|
| newNode | Đây là nút con mới được tạo sẽ được thêm vào ở đầu |
| currentNode | Đây là nút đã tồn tại |
Ví dụ
Hãy để chúng tôi xem một ví dụ cho InsertBefore () phương pháp -
<!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>How to make tea</h1>
<h3>Steps:</h3>
<ol id="stepList">
<li>Add Tea Bag</li>
<li>Add Sugar</li>
<li>Add Milk</li>
</ol>
<input type="button" onclick="addStep()" value="Add">
</fieldset>
</form>
<script>
function addStep() {
var newIngredient = document.createElement("LI");
var textnode = document.createTextNode("Boil Water");
newIngredient.appendChild(textnode);
var stepList = document.getElementById("stepList");
stepList.insertBefore(newIngredient, stepList.childNodes[0]);
}
</script>
</body>
</html> Đầu ra
Điều này sẽ tạo ra kết quả sau -
Trước khi nhấp vào ‘Thêm’ nút -
Sau khi nhấp vào ‘Thêm’ nút -