본문 바로가기
it/web_dev

innerHTML과 appendChild 선언 방식

by holims 2023. 6. 26.

목차

    반응형

    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는 기존의 있는 요소 마지막에 자식으로 새로운 요소를 추가할 수 있는 메서드