04. 텍스트 노드 조작 방법

양희준·2022년 2월 27일
0

DOM

목록 보기
4/8
post-thumbnail

📌 4-1 TextNode란?

HTML의 내용을 가리킨다.

💡 텍스트 노드는 요소 노드의 자식 노드로 존재한다.
💡 Node.prototype의 메소드에서 NodeList를 반환하는 경우 텍스트 노드도 포함되어 있을 수도 있다.

📌 4-2 innerText

🧩 Element.prototype.innerText

✔ innerText 프로퍼티는 CSS에 종속적이다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="title">Hey
            <span id="sub-title">World!</span>
        </div>
    </body>
    <script>
        const $div = document.querySelector("#title");
        // 결과 : Hey -> Hello로 바뀜
        $div.innerText = "Hello";
    </script>
</html>

📌 4-3 TextContent

🧩 Node.prototype.textContent

✔ CSS에 종속적이지 않다.
✔ innerText 보다 성능이 좋다. CSS를 고려하지 않기 때문이다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="title">Hello
            <span id="sub-title">World!</span>
        </div>
    </body>
    <script>
        const $div = document.querySelector("#title");
        // 결과 : Hey로 문자열 바뀜
        $div.textContent = "Hey";
    </script>
</html>

📌 4-4 CSS 종속이란?

innerText와 TextContent로 확인하기.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <style>
        /* 글씨를 안보이게 하는 CSS 추가 */
        #sub-title {
            display: none;
        }
    </style>
    <body>
        <div id="title">Hello
            <span id="sub-title">World!</span>
        </div>
    </body>
    <script>
        const $div = document.querySelector("#title");
        // 결과 : Hello World!
        console.log($div.textContent);
        // 결과 : Hello
        console.log($div.innerText);
        // innerText도 같은결과가 나온다.
        $div.textContent = "JS";
        // div의 자식노드 span 사라져서 출력된다.
        console.log($div.childNodes);
    </script>
</html>

📃 innerText와 textContent 프로퍼티 역시 해당 요소노드의 자식노드를 전부 덮어 쓰는 형태로 되어있다. textContent가 아무리 성능적으로 innerText보다 좋다고는 하지만 많은 코드에서 innerText를 사용함으로 사용유무는 개발자 판단이라고 생각한다.

0개의 댓글