JavaScript Reference ยท DOM: Document and Elements
HTMLElement.innerText
Reference for HTMLElement.innerText: read text as it appears on screen, honoring CSS visibility and line breaks, and how it differs from textContent.
The innerText property represents the rendered text of an element: the text a user would get if they selected the element and copied it. The browser takes CSS into account, so text hidden with display: none is left out, <br> and block elements produce line breaks, and text-transform is applied.
Setting innerText replaces the element's children with text. Newline characters in the string become <br> elements.
const visible = element.innerText; element.innerText = "Line 1\nLine 2";
Try it
Syntax
const text = element.innerText; element.innerText = newText;
| Name | Description |
|---|---|
newText |
A string. Each newline becomes a <br> element, and the other characters become text nodes. |
Return value (getter): a string with the rendered text.
Usage notes
- Layout-aware, so slower. Reading
innerTextmakes the browser compute styles and layout so it knows what is visible. In a loop, prefertextContent, which needs no layout. - Hidden content is skipped. Elements with
display: noneorvisibility: hiddendo not appear. Elements that are not being rendered at all (for example a detached element) return the same text astextContent. - Line breaks follow layout. Block-level elements, table rows and
<br>produce newlines, and runs of whitespace are collapsed as they are on screen.white-space: prekeeps them. - CSS transforms of text.
text-transformis reflected in the result, so the value may differ from what is stored in the DOM. - Only on
HTMLElement. SVG and MathML elements do not have it; usetextContentthere. - Setting is safe from injection. Like
textContent, it never parses HTML, but it does create<br>elements for newlines. - Which to choose. Use
textContentto read or write text data, andinnerTextwhen you want exactly what the user sees, for example to copy or measure visible text.
Browser support
Supported in all current browsers. Early specifications left it out, so very old code sometimes checks for textContent instead.
Related
Node.textContentโ raw text, no layoutElement.innerHTMLโ markupwindow.getComputedStyle()โ check what CSS applies- Lesson: Creating and changing elements