자식 노드 추가,삭제 appendChild, removeChild

자식 노드 추가,삭제 appendChild, removeChild

자식 노드 추가하는 방법:

- html에 있는 태그를 변경하는 것이 아닌 html에 없는 태그 추가하기

const 변수명 = document.createElement("태그명"); -> createElement로 먼저 태그 생성

변수명.setAttribute("속성명", 값); -> .setAttribute("class", "myClass"); 하면 클래스 추가됨

부모노드.appendChild("변수명"); -> 부모노드에 방금 생성한 자식 노드 추가

ex)

function append() { const image = document.createElement("img"); //태그 생성 image.setAttribute("src","img/ball.jpg"); //src 속성 추가 image.setAttribute("class", "ball"); //class 추가 document.form1.appendChild(image); //form1 밑에 자식 노드로 추가 //append1이 실행되면 src,class 속성이 추가된 img 태그가 생성됨 }

자식 노드 삭제하는 방법

- 삭제할때는 무조건 부모 위치에서 삭제해야됨, 형제 위치에서는 삭제 불가

- 객체.parentNode 하면 부모 객체 접근 가능

- 객체.parentNode.removeChild("자식노드객체"); 부모 객체 접근 후 removeChild로삭제

from http://broship.tistory.com/67 by ccl(A) rewrite - 2021-01-27 23:27:18