เมธอด HTML DOM insertBefore() จะแทรกโหนดใหม่ก่อนโหนดย่อยที่มีอยู่แล้ว
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
การเรียก insertBefore() ด้วยพารามิเตอร์ของ positionString และ text
node.insertBefore(newNode, existingNode)
ที่นี่ พารามิเตอร์ สามารถเป็นดังต่อไปนี้ -
พารามิเตอร์
| พารามิเตอร์ | คำอธิบาย |
|---|---|
| โหนดใหม่ | เป็นโหนดย่อยที่สร้างขึ้นใหม่ซึ่งจะต่อท้ายตอนเริ่มต้น |
| โหนดที่มีอยู่ | เป็นโหนดที่มีอยู่แล้ว |
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับ 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>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> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
ก่อนคลิก 'เพิ่ม' ปุ่ม −

หลังจากคลิก 'เพิ่ม' ปุ่ม −
