Element.prototype.textContent
Gets or sets the text content of the node and its descendants
Syntax
element.textContent = textParameters
| Parameter | Type | Description |
|---|---|---|
| text | string | The text content to set |
Return Value
A string representing the text content, or null
Examples
const heading = document.querySelector('h1')!
console.log(heading.textContent)const el = document.getElementById('counter')!
let count = 0
el.textContent = String(count)function stripHtml(html: string): string {
const div = document.createElement('div')
div.innerHTML = html
return div.textContent || ''
}Understanding Element.prototype.textContent
The Element.prototype.textContent method in JavaScript gets or sets the text content of the node and its descendants. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.textContent = text. It accepts 1 parameter: text. When called, it returns a string representing the text content, or null. Understanding when and how to use textContent() helps you write more expressive, readable code.
Common use cases for Element.prototype.textContent include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-innerhtml, dom-outerhtml, dom-createtextnode, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.textContent is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.innerHTMLGets or sets the HTML markup contained within the element
Element.prototype.outerHTMLGets the serialized HTML fragment describing the element including its descendants, or replaces the element with nodes parsed from the given string
document.createTextNodeCreates a new Text node with the specified string as its content
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.