textContent와 innerText의 차이점


157

차이점은 무엇이며 textContent그리고 innerText자바 스크립트는?

textContent다음과 같이 사용할 수 있습니다 :

var logo$ = document.getElementsByClassName('logo')[0];
logo$.textContent = "Example";

3
동일하지만 일부 브라우저는 다른 브라우저를 지원합니다.
Pointy

@Pointy 모든 브라우저가 지원하는 것은 무엇입니까?
Yehia Awad

6
좋은 블로그 게시물 그것에 대해
Tyblitz

4
@Pointy 내가 지적한 블로그 게시물을 참조하십시오. 귀하의 진술이 잘못되었습니다. 차이가 있습니다.
Tyblitz

3
innerText그리고 textContent확실히 동일하지 않습니다. 노드 컨텐츠에서 공백이 발생하면 두 특성이 다른 컨텐츠를 생성하므로 br요소 및 기타 블록 레벨 렌더링 된 자손이 발생합니다.
amn

답변:


211

다른 답변은 전체 설명을 제공하는 데 성공하지 못 하므로이 답변은 없습니다. 사이의 주요 차이점 innerText과는 textContent아주 잘 설명되어 있습니다 켈리 노턴의 블로그 게시물 : innerText와 대는 TextContent . 아래에서 요약을 찾을 수 있습니다.

  1. innerText반면, 비표준이었다 textContent이전 표준화되었다.
  2. innerText반품 보이는 노드에 포함 된 텍스트, 동안 textContent반환 전체 텍스트를. 예를 들어 다음 HTML <span>Hello <span style="display: none;">World</span></span>에서는 innerText'Hello' textContent를 반환하고 'Hello World'를 반환합니다. 더 자세한 차이점 목록은 http://perfectionkills.com/the-poor-misunderstood-innerText/ 의 표를 참조 하십시오 ( 'innerText' 에서 더 읽기 는 Firefox에서는 작동하지만 Firefox에서는 작동하지 않습니다 ).
  3. 결과적으로 innerText성능이 훨씬 높아집니다. 결과를 반환하려면 레이아웃 정보가 필요합니다.
  4. innerTextHTMLElement객체에 대해서만 textContent정의되고 모든 Node객체에 대해 정의 됩니다.

textContentIE8 의 해결 방법 은 지정된 nodeValue모든 childNodes노드 에서 재귀 함수를 사용 하는 것 입니다. 여기에는 polyfill을 시도해보십시오.

function textContent(rootNode) {
  if ('textContent' in document.createTextNode(''))
    return rootNode.textContent;

  var childNodes = rootNode.childNodes,
      len = childNodes.length,
      result = '';

  for (var i = 0; i < len; i++) {
    if (childNodes[i].nodeType === 3)
      result += childNodes[i].nodeValue;
    else if (childNodes[i].nodeType === 1) 
      result += textContent(childNodes[i]);
  }

  return result;
}

16
또한 주목할 가치가 있습니다 : 요소를 개행 문자로 innerText바꾸는 <br>반면 textContent무시할 것입니다. 만 2 개 단어 그래서 <br>그들 (공백없이) 사이의 요소를 사용하는 경우 연결된 것textContent
skerit

5
그러면 세터를 사용할 때 차이점이 있습니까? 마찬가지로 elem.textContent = 'foobar'elem.innerText = 'foobar'
프랭클린 유

1
사이에 동작의 또 다른 차이점 innerTexttextContent: 당신이 변경하는 경우 text-transformCSS에 의해 요소의를, 그것은 'innerText와'의 결과에 영향을 미치지 만이 아닌 결과 것입니다 textContent. 예를 들어 : innerTextof <div style="text-transform: uppercase;">Hello World</div>는 "HELLO WORLD"이고 textContent"Hello World"입니다.
Kobi

25

textContent 텍스트 노드에 사용 가능한 유일한 것입니다.

var text = document.createTextNode('text');

console.log(text.innerText);    //  undefined
console.log(text.textContent);  //  text

요소 노드에서 innerText<br> 요소를 textContent평가하고 제어 문자 를 평가합니다.

var span = document.querySelector('span');
span.innerHTML = "1<br>2<br>3<br>4\n5\n6\n7\n8";
console.log(span.innerText); // breaks in first half
console.log(span.textContent); // breaks in second half
<span></span>

span.innerText 제공합니다 :

1
2
3
4 5 6 7 8

span.textContent 제공합니다 :

1234
5
6
7
8

textContent내용이로 설정된 경우 제어 문자 (예 : 줄 바꿈)가 포함 된 문자열은에서 사용할 수 없습니다 innerText. 다른 방법 (설정 제어 문자와 함께 textContent), 모든 문자가와 모두를 반환 innerText하고 textContent:

var div = document.createElement('div');
div.innerText = "x\ny";
console.log(div.textContent);  //  xy


20

innerTexttextContent모든 2016 년 기준으로 표준화 Node(순수 텍스트 노드 포함) 개체를 가지고 textContent있지만 HTMLElement개체가 있습니다 innerText.

textContent대부분의 브라우저에서 작동 하지만 IE8 이전 버전에서는 작동하지 않습니다. 이 polyfill을 사용하여 IE8에서만 작동하십시오. 이 polyfill은 IE7 이전 버전에서는 작동하지 않습니다.

if (Object.defineProperty 
  && Object.getOwnPropertyDescriptor 
  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") 
  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
  (function() {
    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
    Object.defineProperty(Element.prototype, "textContent",
     {
       get: function() {
         return innerText.get.call(this);
       },
       set: function(s) {
         return innerText.set.call(this, s);
       }
     }
   );
  })();
}

Object.defineProperty방법은 IE9 이상에서 사용할 수 있지만 DOM 객체에 대해서만 IE8에서 사용할 수 있습니다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent


2
: 여기 너무 그것에 대한 스펙이다 w3.org/TR/DOM-Level-3-Core/core.html는 또한 (아주 오래된) 브라우저 지원 테이블 ( webdevout.net/browser-support-dom#dom3core ) 제안은, IE9 이상에서 지원되므로 IE8 이상에서는 innerText친구입니다.
geekonaut

실제로, 즉 ie8을 지원하지 않거나 폴리 필을 사용하는 것이 좋습니다. 내 게시물에 polyfill을 게시
Richard Hamilton

1
해당 폴리 필이 IE8에서 어떻게 지원되지 않을 때 작동 Object.defineProperty()합니까?
Pointy

2
왜 답을 업데이트하지 않습니까? html.spec.whatwg.org/multipage/…
caub

3
다음은 MDN의 innerText에 대한 인용입니다. "이 기능은 Internet Explorer에서 처음 도입되었으며 모든 주요 브라우저 공급 업체에서 채택한 2016 년 HTML 표준에 공식적으로 지정되었습니다."
차드

15

이 질문을 봤고 여기에 도착한 사람들을 위해. 이 질문에 대한 가장 명확한 대답은 MDN 문서 https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent에 있습니다.

당신을 혼란스럽게 할 수 있지만 2 가지를 기억할 수있는 모든 점을 잊어 버릴 수 있습니다

  1. 텍스트를 변경하려고 할 때 textContent일반적으로 찾고있는 속성입니다.
  2. 일부 요소에서 텍스트를 가져 오려고 할 때 innerText커서로 요소의 내용을 강조 표시 한 다음 클립 보드에 복사하면 사용자가 얻는 텍스트 와 비슷합니다. 그리고 textContent당신에게 모든 것을 보이거나 숨겨진 포함 제공 <script><style>요소.


0

textContent는 전체 텍스트를 반환하고 가시성은 신경 쓰지 않지만 innerText는 반환합니다.

<p id="source">
    <style>#source { color: red; }</style>
    Text with breaking<br>point.
    <span style="display:none">HIDDEN TEXT</span>
</p>

textContent의 출력 :

#source { color: red; } Text with breakingpoint. HIDDEN TEXT

innerText의 출력 (innerText가과 같은 태그를 인식 <br>하고 숨겨진 요소를 무시 하는 방법에 유의하십시오 ) :

Text with breaking point.

IE11에서 innerText의 동작은 textContent의 동작과 동일합니다.
Sebastian

0

다른 답변에서 명명 된 모든 차이점 외에도 최근에 만 발견 한 또 다른 것이 있습니다.

innerText속성은 2016 년 이후 표준화 된 것으로 알려져 있지만 브라우저마다 차이점이 있습니다. Mozilla는에서 U + 200E 및 U + 200F 문자 ( "lrm"및 "rlm")를 무시 innerText하고 Chrome은 그렇지 않습니다.

console.log(document.getElementById('test').textContent.length);
console.log(document.getElementById('test').innerText.length);
<div id="test">[&#x200E;]</div>

Firefox 보고서 3 및 2, Chrome 보고서 3 및 3

이것이 버그인지 (그렇다면 브라우저에서) 또는 우리가 살아야하는 기발한 비 호환성 중 하나인지 확실하지 않습니다.


-1

innerHTML은 HTML 기반 태그를 실행하여 DOM 기반 XSS와 같은 클라이언트 측 주입 공격을 유발할 위험이 있습니다. 다음은 코드 스 니펫입니다.

<!DOCTYPE html>
<html>
    <body>
        <script>
            var source = "Hello " + decodeURIComponent("<h1>Text inside gets executed as h1 tag HTML is evaluated</h1>");  //Source
            var divElement = document.createElement("div");
            divElement.innerHTML = source;  //Sink
            document.body.appendChild(divElement);
        </script>
    </body>
</html>

.textContent를 사용하면 HTML 태그를 평가하지 않고 문자열로 인쇄합니다.

<!DOCTYPE html>
<html>
    <body>
        <script>
            var source = "Hello " + decodeURIComponent("<h1>Text inside will not get executed as HTML</h1>");  //Source
            var divElement = document.createElement("div");
            divElement.textContent = source;  //Sink
            document.body.appendChild(divElement);
        </script>
    </body>
</html>

참조 : https://www.scip.ch/en/?labs.20171214

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.