--- title: Node.textContent slug: Web/API/Node/textContent translation_of: Web/API/Node/textContent ---
{{APIRef("DOM")}}

Node.textContent 屬性表示了節點或其後代的文字內容。

語法

var text = element.textContent;
element.textContent = "this is some sample text";

描述

與 innerText 的差異

Internet Explorer introduced element.innerText. The intention is similar but with the following differences:

innerHTML 的差異

innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

範例

// Given the following HTML fragment:
//   <div id="divA">This is <span>some</span> text</div>

// Get the text content:
var text = document.getElementById("divA").textContent;
// |text| is set to "This is some text".

// Set the text content:
document.getElementById("divA").textContent = "This is some text";
// The HTML for divA is now:
//   <div id="divA">This is some text</div>

Polyfill for IE8

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);
       }
     }
   );
  })();
}

瀏覽器相容性

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1+ 2 9 9.64 (possibly earlier) 3 (possibly earlier)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

規範

Specification Status Comment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}} {{Spec2('DOM WHATWG')}} No changes versus DOM4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}} {{Spec2('DOM4')}}  
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}} {{Spec2('DOM3 Core')}} Introduced

參見