목차
반응형
innerHTML이 중복으로 선언되면 최신으로 선언된 것만 출력
appendChild은 부모 요소에서 자식 요소를 하나의 노드만 추가 할 수 있는 메서드
코드로 확인
index.html
<div id="root"></div>
<script src="index.js" type="module" />
자식 요소가 없는 id값이 root인 div요소 선언
index.js
import List from "./list.js";
const $root = document.getElementById("root");
$root.innerHTML = `<div>Hello</div>`;
new List({ $root });
id값이 root인 div를 변수 $root로 지정하여 innerHTML을 이용하여 자식 요소로 hello내용인 div요소 넣기
list.js
export default function List({ $root }) {
$root.innerHTML = `<div>This Container</div>`
}
list.js에서 $root.innerHTML만 선언 되어 있으면 index.js의 $root.InnerHTML 이 덮어 씌어지게 되어 Hello가 출력 되지 않고 This Container가 출력된다.
list.js
export default function List({ $root }) {
const $container = document.createElement("div");
$container.innerText = `<div>This Container</div>`;
$root.appendChild($container);
}
list.js의 $root.innerHTML을 삭제하고, appendChild를 추가하면 $container.innerHTML가 부모 요소인 <div id="root">에 추가 된다.
HTML로 풀어보면
<div id="root">
<div>Hello</div>
<div>This Container</div>
</div>
결론
innerHTML은 기존의 있던 요소 모두 변경 가능하기 떄문에 새로운 요소만 추가할 수 있는 프로퍼티
appendChild는 기존의 있는 요소 마지막에 자식으로 새로운 요소를 추가할 수 있는 메서드
'it > web_dev' 카테고리의 다른 글
동적 타입 시스템 (0) | 2023.06.26 |
---|---|
javascript의 배열을 객체로 변경하기 (0) | 2023.06.26 |
MVC 아키텍처: 웹 개발에서의 구조적 효율성과 유지보수성 (0) | 2023.06.26 |
node.js 개발을 위한 필수 라이브러리 (0) | 2023.06.26 |
타입스크립트 이해하기 (0) | 2023.06.26 |