HTML DOM의 insertAdjacentElement() 메서드는 지정한 위치에 새로운 요소(element)를 삽입하는 기능을 제공합니다. 이 메서드를 활용하면 기존 DOM 구조를 유지하면서 특정 요소를 기준으로 원하는 자리에 다른 요소를 간편하게 추가할 수 있습니다.
문법(Syntax)
insertAdjacentElement() 메서드는 아래와 같은 형식으로 호출합니다. 첫 번째 매개변수로 삽입 위치를 나타내는 positionString을, 두 번째 매개변수로 삽입할 element를 전달합니다.
node.insertAdjacentElement("positionString", element)
positionString 종류
"positionString" 매개변수에는 다음 네 가지 값 중 하나를 사용할 수 있습니다.
| positionString | 설명 |
|---|---|
| beforebegin | 노드 요소의 바로 앞(외부 이전 위치)에 요소를 삽입합니다. |
| afterbegin | 노드 요소 내부 시작 지점 직후에 요소를 삽입합니다. |
| beforeend | 노드 요소 내부 끝 지점 직전에 요소를 삽입합니다. |
| afterend | 노드 요소의 바로 뒤(외부 다음 위치)에 요소를 삽입합니다. |
예제
아래 예제는 insertAdjacentElement() 메서드를 사용해 잘못된 순서로 표시된 가족 관계도를 버튼 클릭 한 번으로 올바르게 수정하는 코드입니다.
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentElement()</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentElement( )</legend>
<h1>Family Tree</h1>
<span id="Father">Father --></span>
<span id="GrandFather">Grand Father --></span>
<span id="Myself">Myself</span>
<input type="button" onclick="rectifyTree()" value="Correct Family Tree">
</fieldset>
</form>
<script>
function rectifyTree() {
var FSpan = document.getElementById("Father");
var GFSpan = document.getElementById("GrandFather");
GFSpan.insertAdjacentElement("afterend", FSpan);
}
</script>
</body>
</html>
위 코드에서는 "afterend" 옵션을 사용하여 'Father' 요소를 'GrandFather' 요소의 바로 뒤로 이동시킵니다. 결과적으로 GrandFather → Father → Myself 순서의 올바른 가족 관계도가 완성됩니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면을 확인할 수 있습니다.
'Correct Family Tree' 버튼 클릭 전 −

'Correct Family Tree' 버튼 클릭 후 −
