Ατρ. textContent του HTML DOM Element
- Προηγούμενη Σελίδα tagName
- Επόμενη Σελίδα title
- Επιστροφή στο Προηγούμενο Στρώμα Σύνολο Elements του HTML DOM
Ορισμός και χρήση
textContent
Αυτό το ατρ. ορίζει και επιστρέφει το κείμενο του καθορισμένου κόμβου και όλων των απογόνων του.
Αν ρυθμίσετε textContent
Αυτό το ατρ., αφαιρεί όλα τα υποστοιχεία και αντικαθιστά τα με μια μοναδική κείμενη κόμβο που περιέχει τη δεδομένη αλφαβητική ακολουθία.
Συμβουλή:Σε ορισμένες περιπτώσεις, αυτό το ατρ. μπορεί να αντικαταστήσει το ατρ. nodeValue, αλλά θυμηθείτε ότι αυτό το ατρ. επιστρέφει το κείμενο όλων των υποστοιχείων.
Δείτε επίσης:
Παράδειγμα
Παράδειγμα 1
Επιστρέψτε το κείμενο του στοιχείου:
let text = element.textContent;
Παράδειγμα 2
Αλλάξτε το κείμενο του στοιχείου <p> με id="demo":
element.textContent = "I have changed!";
Παράδειγμα 3
Αποκτήστε το όλον κείμενο του στοιχείου <ul> με id="myList":
let text = document.getElementById("myList").textContent;
Syntax
Return the text content of the node:
element.textContent
or
node.textContent
Set the text content of the node:
element.textContent = text node.textContent = text
Attribute Value
Value | Description |
---|---|
text | Text content of the element or node. |
Return Value
Type | Description |
---|---|
String |
Text content of the element and all its descendants. Returns null if the element is document, document type, or notation. |
Difference between innerHTML, innerText, and textContent
The innerText property returns:
Returns only the text content of the element and all its children, without CSS hidden text spacing and tags, except for <script> and <style> elements.
The innerHTML property returns:
Text content of the element, including all whitespace and internal HTML tags.
The textContent property returns:
Text content of the element and all its descendants, including whitespace and CSS hidden text, but without tags.
HTML Example
<p id="myP"> This element has extra spacing and contains <span>a span element</span>.</p>
Παραδείγματα JavaScript
let text = document.getElementById("myP").innerText; let text = document.getElementById("myP").innerHTML; let text = document.getElementById("demo").textContent;
In the above example:
The innerText property returns:
This element has extra spacing and contains a span element.
The innerHTML property returns:
This element has extra spacing and contains <span>a span element</span>.
The textContent property returns:
This element has extra spacing and contains a span element.
Browser support
element.textContent
It is a DOM Level 3 (2004) feature.
All browsers fully support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Υποστήριξη | 9-11 | Υποστήριξη | Υποστήριξη | Υποστήριξη | Υποστήριξη |
- Προηγούμενη Σελίδα tagName
- Επόμενη Σελίδα title
- Επιστροφή στο Προηγούμενο Στρώμα Σύνολο Elements του HTML DOM