HTML DOM의 insertBefore() 메서드는 이미 존재하는 자식 노드 앞에 새로운 노드를 삽입할 때 사용합니다. 이 메서드를 활용하면 리스트 항목이나 특정 요소 사이에 동적으로 새로운 콘텐츠를 추가할 수 있습니다.
문법(Syntax)
insertBefore() 메서드의 기본 문법은 다음과 같습니다.
node.insertBefore(newNode, existingNode)
매개변수(Parameters)
각 매개변수의 의미는 아래 표와 같습니다.
| 매개변수 | 설명 |
|---|---|
| newNode | 삽입할 새롭게 생성된 자식 노드 |
| existingNode | 기준이 되는 기존 노드 (이 노드 앞에 newNode가 삽입됨) |
예제(Example)
다음은 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>차 만드는 방법</h1>
<h3>단계:</h3>
<ol id="stepList">
<li>티백 넣기</li>
<li>설탕 넣기</li>
<li>우유 넣기</li>
</ol>
<input type="button" onclick="addStep()" value="추가">
</fieldset>
</form>
<script>
function addStep() {
var newIngredient = document.createElement("LI");
var textnode = document.createTextNode("물 끓이기");
newIngredient.appendChild(textnode);
var stepList = document.getElementById("stepList");
stepList.insertBefore(newIngredient, stepList.childNodes[0]);
}
</script>
</body>
</html>코드 설명
- document.createElement("LI") : 새로운 <li> 요소를 생성합니다.
- document.createTextNode() : 삽입할 텍스트 노드('물 끓이기')를 만듭니다.
- appendChild(textnode) : 생성한 텍스트를 새 <li> 요소에 추가합니다.
- stepList.insertBefore(newIngredient, stepList.childNodes[0]) : 목록의 첫 번째 자식 노드 앞에 새 항목을 삽입합니다.
실행 결과(Output)
위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.
'추가' 버튼 클릭 전 –

'추가' 버튼 클릭 후 –

버튼을 클릭하면 '물 끓이기' 항목이 목록의 첫 번째 위치에 삽입되는 것을 확인할 수 있습니다. 이처럼 insertBefore() 메서드는 DOM 구조에서 원하는 위치에 정확히 노드를 배치해야 할 때 유용하게 활용됩니다.