JavaScript insertBefore() 메서드로 기존 자식 노드 앞에 새 노드 삽입하기
JavaScript는 insertBefore() 메서드를 통해 기존 자식 노드 앞에 새로운 노드를 자식으로 삽입할 수 있도록 지원합니다. 두 개의 목록이 있을 경우 이 메서드를 활용하면 요구 사항에 맞게 목록 간의 요소를 자유롭게 재배치할 수 있습니다.
구문
node.insertBefore(newnode, existingnode);
- newnode: 삽입할 새로운 노드
- existingnode: 새 노드가 그 앞에 위치하게 될 기존 자식 노드
예제 1
다음 예제에는 두 개의 목록이 있으며, insertBefore() 메서드를 사용해 요구 사항에 따라 목록 요소를 재배열합니다. 목록의 여러 요소에 접근하려면 인덱스를 활용하면 됩니다.
<html>
<body>
<ul id="List1"> <li>Tesla </li><li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[1]);
</script>
</body>
</html>출력 결과
Tesla Google Solarcity Drupal
위 코드에서는 List2의 첫 번째 자식 노드(Google)를 가져온 뒤, List1의 두 번째 자식 노드(Solarcity) 앞에 삽입합니다. 그 결과 Google이 Tesla와 Solarcity 사이로 이동한 것을 확인할 수 있습니다.
예제 2
이번에는 기준 노드를 목록의 첫 번째 요소로 지정한 예제입니다. childNodes[0]을 기준으로 삽입하면 새 노드가 목록의 맨 앞에 추가됩니다.
<html>
<body>
<ul id="List1"> <li>Tesla </li> <li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[0]);
</script>
</body>
</html>출력 결과
Google Tesla Solarcity Drupal
이처럼 insertBefore() 메서드의 두 번째 인자로 어떤 자식 노드를 지정하느냐에 따라 새 노드가 삽입되는 위치가 달라집니다. 참고로 기준 노드를 null로 지정하면 노드가 목록의 맨 끝에 추가되므로, 이 특성까지 함께 기억해 두면 DOM 조작 시 매우 유용합니다.