[자바스크립트] innerText 와 textContent 차이점
 

innerText의 Syntax

const renderedText = htmlElement.innerText
htmlElement.innerText = string

textContent의 Syntax

let text = someNode.textContent
someOtherNode.textContent = string

MDN에 innerText와 textContent 비교한게 있다.

(출처 게시글 밑 참고)

HTML:

<h3>Source element:</h3>
<p id="source">
<style>#source { color: red; }</style>
Take a look at<br>how this text<br>is interpreted below.
<span style="display:none">HIDDEN TEXT</span>
</p>
<h3>Result of textContent:</h3>
<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
<h3>Result of innerText:</h3>
<textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea>

자바스크립트:

const source = document.getElementById('source');
const textContentOutput = document.getElementById('textContentOutput');
const innerTextOutput = document.getElementById('innerTextOutput');
 
textContentOutput.innerHTML = source.textContent;
innerTextOutput.innerHTML = source.innerText;

결과:

- innerText는 <br> 태그를 인식한다.

- display:none인 요소를 무시한다.


차이점 :

- innerText is aware of the rendered appearance of text, while textContent is not.

innerText는 텍스트의 렌더링 된 모습을 인식하지만, textContent는 아니다.

이 말은 즉, 요소 자체가 렌더링 중이 아니라면 Node.innertText Node.textContent 속성의 값과 동일하다.

- textContent 가 먼저 만들어졌다. 정도..

공통점과 차이점에 대해서는 이 사이트에 더 자세히 나와있다.


참고:

320x100