Node
인터페이스의 textContent
속성은 노드와 그 자손의 텍스트 콘텐츠를 표현
let text = someNode.textContent
someOtherNode.textContent = string
HTMLElement.innerText의 이름이 유사하긴 하지만, 중요한 차이가 존재
<script>
와 <style>
요소를 포함한 모든 요소의 콘텐츠를 가져온다. 반면 innerText
는 "사람이 읽을 수 있는 요소"만 처리
Element.innerHTML
는 이름 그대로 HTML을 반환한다. 간혹 innerHTML을 사용해 요소의 텍스트를 가져오거나 쓰는 경우가 있지만, HTML로 분석할 필요가 없다는 점에서textContent
의 성능이 더 좋다.textContent
는 XSS공격의 위험이 없다.
<div id="divA">This is <span>some</span> text!</div>
let text = document.getElementById('divA').textContent;
// The text variable is now: 'This is some text!'
document.getElementById('divA').textContent = 'This text is different!';
// The HTML for divA is now:
// <div id="divA">This text is different!</div>