JS DOM 증감실습, innerHTML, innerText, textContent의 차이점

tpids·2024년 6월 11일

JS

목록 보기
29/40
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="num">0</p>
    <button onclick="increse()">증가</button>
    <button onclick="decrease()">감소</button>
    <script>
        // 버튼 클릭 시, 숫자를 카운팅하는 실습

        const increse = () => {
            // 1. 숫자정보를 가진 p요소객체 접근
            let num = document.getElementById('num')

            // 2. p요소객체의 콘텐츠(내용)을 +1을 적용하여 초기화
            let currentNumber = parseInt(num.innerText); // 모든 innerText를 TextContent로 바꿔서 써도 됨
            num.innerText = currentNumber + 1;


        }

        const decrease = () => {
           
            let num = document.getElementById('num')

            // 현재 숫자 값을 확인
            let currentNumber = parseInt(num.innerText);

             // 3. 음수가 되면 안된다 -> 조건을 하나 생성
            if (currentNumber > 0) {
                num.innerText = currentNumber - 1;
            }

        } 

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

innerHTML, innerText, textContent의 차이점

innerHTML

  • innerHTML은 'Element'의 속성으로, 해당 Element의 HTML, XML을 읽어오거나, 설정할 수 있습니다.

innerText

  • innerText는 'Element'의 속성으로, 해당 Element 내에서 사용자에게 '보여지는' 텍스트 값을 읽어옵니다.

  • 'display:none'으로 정의된 '숨겨진 텍스트'는 브라우저에서 사용자에게 보여지지 않습니다.

textContent

  • textContent는 'Node'의 속성으로, innetText와는 달리 script나 style 태그와 상관없이 해상 노드가 가지고 있는 텍스트 값을 그대로 읽습니다.

  • 'display:none' 스타일이 적용된 '숨겨진 텍스트' 문자열도 그대로 출력

profile
개발자 공부중

0개의 댓글