HTML DOM의 insertAdjacentText() 메서드는 지정한 위치에 텍스트 문자열을 삽입하는 기능을 제공합니다. 요소의 내부나 외부 원하는 지점에 간단히 텍스트를 추가할 수 있어 동적인 웹 페이지를 만들 때 유용하게 활용됩니다.
문법(Syntax)
insertAdjacentText() 메서드는 위치 문자열(positionString)과 삽입할 텍스트(text) 두 개의 매개변수를 받아 호출합니다.
node.insertAdjacentText("positionString", text)위치 문자열(Position Strings)
positionString 매개변수에는 아래 네 가지 값을 사용할 수 있습니다.
| positionString | 설명 |
|---|---|
| afterbegin | 요소(node)의 시작 태그 바로 뒤에 텍스트를 삽입합니다. 즉, 요소 내부의 맨 앞에 추가됩니다. |
| afterend | 요소 바로 뒤(외부)에 텍스트를 삽입합니다. |
| beforebegin | 요소 바로 앞(외부)에 텍스트를 삽입합니다. |
| beforeend | 요소의 종료 태그 바로 앞에 텍스트를 삽입합니다. 즉, 요소 내부의 맨 뒤에 추가됩니다. |
예제
다음은 insertAdjacentText() 메서드의 실제 사용 예시입니다. 버튼을 클릭하면 대통령 이름 앞에 'DR.'이라는 텍스트가 자동으로 추가되는 예제입니다.
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentText()</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>insertAdjacentText( )</legend>
<h1>인도 최초의 무슬림 출신 대통령</h1>
<h2 id="president">A.P.J Abdul Kalam</h2>
<input type="button" onclick="rectifyName()" value="Correct Name">
</fieldset>
</form>
<script>
function rectifyName() {
var presidentH2 = document.getElementById("president");
presidentH2.insertAdjacentText("afterbegin", "DR. ");
}
</script>
</body>
</html>실행 결과
위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.
'Correct Name' 버튼을 클릭하기 전 −

'Correct Name' 버튼을 클릭한 후 −

버튼을 클릭하면 afterbegin 위치 문자열에 의해 h2 요소 내부 맨 앞에 'DR.'이라는 텍스트가 삽입되어 이름이 'DR. A.P.J Abdul Kalam'으로 변경된 것을 확인할 수 있습니다.