innerHTML, innerText, textContent

김민기·2022년 8월 25일
0

JavaScript-Study

목록 보기
1/12

바닐라 자바스크립트로 SPA 애플리케이션을 만들면서 HTML을 동적으로 만들기 위해서 innerHTML을 자주 사용했다. 하지만 HTML에서 텍스트를 추가하는 방법은 innerHTML 뿐만아니라 innerText, textConent를 사용할 수 있는 것으로 알고 있어서 어떤 차이가 있을지 궁금해서 검색해 보았다.

What’s Best: innerText vs. innerHTML vs. textContent

<div id="text">
     This element is <strong>strong</strong> and      has some super fun     <code>code</code>
</div>

이 div태그의 텍스트를 innerHTML, innerText, textConent를 사용해서 가져와본다.

innerHTML

const getValue = document.getElementById('text');
console.log(getValue.innerHTML);

    This element is <strong>strong</strong> and      has some super fun <code>code</code>

innerHTML을 사용하면 div 태그 내부의 공백, 개행등을 포함하여 내부 문자열과 문자열에 포함된 HTML 마크업을 모두 출력하는 것을 확인할 수 있다.

추가적으로 텍스트에 &, < 또는 > 문자가 포함된 경우 innerHTML은 이러한 문자를 HTML 엔터티 &, <, >로 반환한다.

innerText

const getValue = document.getElementById('text');
console.log(getValue.innerText);
This element is strong and has some super fun code

innerText를 사용하면 텍스트의 공백, 개행, 태그 모두 사라지고 text만 출력되는 것을 확인할 수 있다.
이 text는 렌더링되어 화면에 보여지는 텍스트와 같다.

textContent

const getValue = document.getElementById('text');
console.log(getValue.textContent);

    This element is strong and      has some super fun code
    

textContent를 사용하면 공백, 개행은 모두 유지되지만 태그는 모두 사라지게 된다.

0개의 댓글