javascript

javascript_(Dom_교체,삭제)_22.05.03(day10)

양빵빵 2022. 5. 3. 17:40

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <ul id="fruits">
       <li class="apple">
           <a href="#">사과</a>
        </li>
   </ul>

   <script>
       const $fruits = document.getElementById('fruits');

       //사과 li 요소노드를 취득
       const $apple = $fruits.firstElementChild;

       // $apple의 사본 (얕은 복사: 자기 자신 요소노드만 복제)
       const $shallow = $apple.cloneNode(false);
       console.log($shallow);

       //$apple의 사본(깊은 복사:자기 자신포함 모든 후손노드를 복제)
       const $deep = $apple.cloneNode(true)
       console.log($deep);


   </script>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <ul id="fruits">
        <li>사과</li>
        <li>딸기</li>
        <li>자몽</li>
        <li>라임</li>
        <li>레몬</li>
        <li>바나나</li>
    </ul>
    <script>
        const $fruits = document.getElementById('fruits'); // 기준설정 fruits
        const $mango = $fruits.firstElementChild.cloneNode(); // 얕은 복사
        $mango.textContent = '망고';

        //노드교체 (사과 -> 망고 (태그까지 교체 하고자 할때))

        $fruits.replaceChild($mango, $fruits.firstElementChild);

        //노드삭제
        $fruits.removeChild($fruits.lastElementChild);


        //노드 전체삭제 함수 정의
        //$parentNode:삭제될 자식들의 부모

        /*
        function removeAllchild($parentNode) {

            for (i = 0; i < $parentNode.children.length; i++) {
               
                $parentNode.removeChild($parentNode.children[i]);
                console.log('hi');
            }

        }

        // 유사배열의 문제로 딸기, 라임이 지워지지 않음 (0번 인덱스가 지워지면서 자리가 바뀜)
 */
        function removeAllchild($parentNode) {
            while (!!$parentNode.children.length) {
                $parentNode.removeChild($parentNode.firstElementChild);
            }

     

            //parentNode에 자식이 있는 동안에 첫번째 자식을 지워라.
        }
        removeAllchild($fruits);
    </script>
</body>

</html>