Method |
Description |
document.createElement() |
엘리먼트 만들기 |
document.removeChild() |
자식요소 지우기 |
document.appendChild() |
자식요소 추가 |
document.replaceChild() |
자식요소 교체 |
document.createElement()
HTML 문서에서, Document.createElement() 메서드는 지정한 tagName의 HTML 요소를 만들어 반환합니다. tagName을 인식할 수 없으면 HTMLUnknownElement를 대신 반환합니다.
let element = document.createElement(tagName[, options]);
매개변수
tagName: 생성할 요소의 유형을 가리키는 문자열.
options: Optionalis 속성 하나를 가진 ElementCreationOptions 객체. 속성의 값은 customElements.define()을 사용해 정의한 사용자 정의 요소입니다.
반환 값
새로운 Element.
document.appendChild()
.createElement(h1) : h1 엘리먼트를 만든다.
<h1></h1>
.createTextNode("텍스트") : 선택한 엘리먼트에 텍스트를 추가한다.
function addList(){
var tNode=document.getElementById("val").value;
//입력한 text를 tNode에 저장한다.
var myList=document.getElementById("myList");
//추가할 태그 준비
var list=document.createElement("li");
//li 요소를 만들어서 list에 저장
var txt=document.createTextNode(tNode);
//입력한 text를 저장한 변수 tNode를 이용해서 노드를 만들어 저장
list.appendChild(txt); //append함수 IE에서 안됨
//저장한 노드를 이용해서 li를 만듬
myList.appendChild(list);
//요소를 추가
}
document.removeChild()
HTML 엘리먼트를 제거하려면 해당 엘리먼트 부모의 removeChild() 메서드를 이용하면 된다
document.getElementById("btn2").addEventListener("click",function(){
var btns=document.querySelectorAll(".bClass"); //bClass를 가진 엘리먼트들을 저장한다.
//반복문으로 전체 삭제
document.body.removeChild(btns[0]); //body태그의 자식 중 bClass를 가진 엘리먼트 중 첫째를 삭제한다.
})
//리스트 삭제
document.getElementById("btn2").addEventListener("click",function(){
var list=document.getElementById("myList"); //ul태그
console.log(list);
console.log(list.childNodes);
list.removeChild(list.childNodes[list.childNodes.length-1]);
});
document.replaceChild()
메소드는 특정 부모 노드의 한 자식 노드를 다른 노드로 교체합니다.
replacedNode = parentNode.replaceChild(newChild, oldChild);
- newChild는 oldChild를 교체할 새로운 노드입니다. 만약 이미 DOM 안에 존재한다면 가장 먼저 제거됩니다.
- oldChild는 이미 존재하는, 교체될 자식 노드입니다.
- replacedNode는 교체된 노드입니다. oldChild와 동일한 노드입니다.
var textNode=document.createTextNode("Water");
var item=document.getElementById("myList").childNodes[0];
item.replaceChild(textNode,item.childNodes[0]);
<body>
<input id="val" type="text">
<button type="button" onclick="addList()">추가</button>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li></ul>
<button id="btn1"> 엘리먼트 추가</button>
<button id="btn2"> 엘리먼트 삭제</button>
<button id="btn3"> 엘리먼트 교체</button>
</body>
-부모자식 관계
body의 자식: <input>, <button>, <ul>,
ul의 자식: <li>
li의 자식: Coffee, Tea, Milk
'javascript' 카테고리의 다른 글
setInterval(), clearInterval(), setTimeout() 함수 (0) | 2019.11.27 |
---|---|
Location, history.back, history.forward 함수 (0) | 2019.11.27 |
엘리먼트 속성 변경 (0) | 2019.11.27 |