[TIL]

Dev_min·2020년 4월 28일
0

Node.textContent

Node 인터페이스의 textContent 속성은 노드와 그 자손의 텍스트 콘텐츠를 표현

let text = someNode.textContent
someOtherNode.textContent = string

innerText 와의 차이점

HTMLElement.innerText의 이름이 유사하긴 하지만, 중요한 차이가 존재

  • textContent는 <script><style> 요소를 포함한 모든 요소의 콘텐츠를 가져온다. 반면 innerText는 "사람이 읽을 수 있는 요소"만 처리
  • textContent는 노드의 모든 요소를 반환한다. 그에 비해 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>
profile
TIL record

0개의 댓글