HTML DOM insertBefore() 메서드는 이미 존재하는 자식 노드 앞에 새 노드를 삽입합니다.
구문
다음은 구문입니다 -
positionString 및 text의 매개변수를 사용하여 insertBefore() 호출
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> 출력
이것은 다음과 같은 출력을 생성합니다 -
'추가'를 클릭하기 전에 버튼 -

'추가'를 클릭한 후 버튼 -
