새소식

Frontend/JavaScript

[JavaScript] innerHTML, innerText, textContent

  • -

 

innerHTML

 

  • value: string
  • 모든 자손를 삭제하고 innterHTML의 value 값으로 들어온 string 타입의 HTML 노드로 대체
  • 페이지를 처음 로딩했을 때 발생한 변화를 비롯해 페이지의 최신 HTML 소스를 검사하는 데 사용 가능

 

 

용도

1.요소의 HTML 콘텐츠를 읽음

let contents = myElement.innerHTML; // string 요소 반환

 

2.요소의 콘텐츠 대체

innerHTML에 값을 부여하면 원래 있던 요소의 콘텐츠를 새롭게 대체

 

도큐먼트 안의 바디 속성을 모두 지우고 싶을 때

document.body.innerHTML = ‘’;

 

값을 추가할 때

element.innerHTML += `<tag>${element.children.length + 1}</tag>`

 

cross-site scripting 위험(XSS) 

innerHTML에 넣은 <script> 태그는 실행하지 않음

하지만 <script> 태그를 쓰지 않아도 자바스크립트를 실행하는 보안 위험이 있음

 

따라서 Element.setHTML() 또는 Node.textContent를 권유

 

Elemenet.setHTML(): remove any illegal character from the data and inserted into the DOM

Node.textContent: 일반 텍스트 삽입시 HTML로 파싱하기보다는 가능한한 텍스트 고유의 상태로 삽입

 

프로젝트가 보안 검사 같은 형태면 innerHTML 사용 코드는 거부당할 것

 

 

innerText

 

  • value: string
  • HTML요소의 innerText 속성은 노드의 렌더링된 텍스트 콘텐츠와 자손을 나타냄
  • 노드에 innerText 속성 부여시 모든 노드의 자식을 제거하고 부여한 하나의 텍스트 노드로 대체함

 

 

textContent

 

  • value: A string or null
  • 노드에 따라서 다른 값 반환
  • 노드에 textContent 속성 부여시 모든 노드의 자식을 제거하고 부여한 하나의 텍스트 노드로 대체함

 

 

 

innerText vs textContent

innerText

  • 사람이 읽을 수 있는 요소만 보여줌
  • 숨겨진 요소(display: none)의 텍스트는 보여주지 않음
  • CSS 스타일을 고려하기 때문에 innerText의 값을 읽으면 최신 계산값을 반영하기 위해 리플로우가 발생
    (리플로우 계산은 비싸므로 가능하면 피해야 함)
reflow
- 웹 인터랙션이 발생해 브라우저 렌더링 과정의 레이아웃을 반복하는 과정
영상

 

textContent

  • <script>, <style> 요소를 포함한 모든 요소의 내용을 보여줌
  • 노드의 모든 요소를 반환

 

See the Pen innerText vs textContent by Yejin Woo (@Yejin-Woo) on CodePen.

 

 

 

 

innerHTML vs textContent

  • textContent 값을 HTML 파싱하지 않아 성능이 더좋고 XSS attack 방지함

 

 


 

 

결론

가급적 XSS 방지를 위해 textContent를 사용하자.

브라우저 렌더링에 대해 공부하자

 


 

 

자료 출처

 

 

Element: innerHTML property - Web APIs | MDN

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

developer.mozilla.org

 

HTMLElement: innerText property - Web APIs | MDN

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants.

developer.mozilla.org

 

Node: textContent property - Web APIs | MDN

The textContent property of the Node interface represents the text content of the node and its descendants.

developer.mozilla.org

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.