js
JS - DOM 요소를 추가 (또는 삭제)하기
새로운 엘리먼트를 만들어서 문서에 추가하거나 원하는 엘리먼트를 삭제할 수 있습니다. 사용할 수 있는 속성은 다음 표와 같습니다.
a 태그의 문자열 끝에 "php" 문자를 추가합니다.
메서드 | 설 명 |
---|---|
createElement() | 새로운 요소를 만듬 |
createTextNode() | 요소에 텍스트를 추가 |
cloneNode() | 선택한 요소의 속성과 해당 값을 복제함 true | false 중 하나. true 이면 하위의 모든 자손을 복제합니다. |
appendChild() | 해당 요소를 문서에 추가 |
insertBefore() | 해당 요소를 문서의 원하는 위치에 추가 |
removeChild() | 해당 요소를 제거. 이때 속성과 텍스트 모두 삭제됩니다. |
createElement()
새로운 input 요소를 만들어 문서에 추가합니다.<h4>하보니 php</h4>
<script>
var input = document.createElement("input");
input.type = "text";
input.name = "you_name";
input.value = "하보니";
// <input type="text" name="you_name" value="하보니">
document.body.appendChild(input);
</script>
createTextNode()
새로운 요소를 만들고 텍스트를 삽입해야 할 때는 createTextNode() 를 사용합니다. 아래는 <a>태그를 만들어 문서에 삽입합니다.<script>
var a = document.createElement("a");
a.href = "http://habonyphp.com";
a.target = "_blank";
var textnode = document.createTextNode("하보니 php");
a.appendChild(textnode);
// <a href="http://habonyphp.com" target="_blank">하보니 php</a>
document.body.appendChild(a);
</script>
a 태그의 문자열 끝에 "php" 문자를 추가합니다.
<a href="http://habonyphp.com" target="_blank">하보니</a>
<script>
var a = document.getElementsByTagName("a")[0];
a.appendChild(
document.createTextNode(" php")
);
// <a href="http://habonyphp.com" target="_blank">하보니 php</a>
document.body.appendChild(a);
</script>
cloneNode()
createElement() 로 새로운 요소를 만드는 게 번거로울 수 있습니다. 그래서 매번 새로운 요소를 만들기 보다 해당 요소를 복제해서 추가해 줄 수 있습니다.<ul id="list1">
<li>크롬</li>
<li>파이어폭스</li>
</ul>
<ul id="list2">
<li>사파리</li>
<li>익스플로어</li>
</ul>
<button onclick="clone()">복제</button>
<script>
function clone() {
// 선택한 요소의 모든 자손을 복제하기 위해 true 로 설정
// id 속성이 list1 인 것을 복제해서
// id 속성이 list2 인 요소에 삽입합니다.
var node = document.getElementById("list1").cloneNode(true);
document.getElementById("list2").appendChild(node);
}
/*
결과:
<ul id="list2">
<li>사파리</li>
<li>익스플로어</li>
<ul id="list1">
<li>크롬</li>
<li>파이어폭스</li>
</ul>
....
</ul>
*/
</script>
insertBefore()
appendChild() 는 문서의 끝에 추가되는 반면 insertBefore() 는 원하는 위치에 요소를 추가할 수 있습니다.<!-- children[0] -->
<h4>하보니 php</h4>
<!-- 여기에 새로운 요소가 삽입됩니다. -->
<!-- children[1] -->
<p>본문</p>
<script>
var input = document.createElement("input");
input.type = "text";
input.name = "you_name";
input.value = "하보니";
// children[1] 은 두 번째 요소를 말하므로
// p 요소 바로 앞에 input 요소를 추가합니다.
document.body.insertBefore(input, document.body.children[1]);
</script>
removeChild()
removeChild() 는 원하는 요소를 삭제합니다.<!-- children[0] -->
<h4>하보니 php</h4>
<!-- children[1] -->
<p>본문1</p>
<!-- children[2] -->
<p>본문2</p>
<script>
// p 태그의 "본문1"을 삭제합니다.
document.body.removeChild( document.body.children[1] );
</script>
0 댓글