XML DOM textContent Property
Definition and Usage
textContent
The property returns or sets the text of the selected element.
When returning text, this property returns the value of all text nodes within the element node.
When setting text, this property will delete all child nodes and replace them with a single text node.
Note:This property does not work in Internet Explorer 9 (returns undefined).
Tip:To set and return the text value of a node, please use the nodeValue property of the text node.
Syntax
Return text:
elementNode.textContent
Set text:
elementNode.textContent=string
Instance
Example 1
The following code loads "books.xml" into xmlDoc, and retrieves the text node from the first <title> element:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); {} }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("title")[0]; document.getElementById("demo").innerHTML = "Text Nodes: " + x.textContent; {}
Example 2
The following code loads "books.xml" into xmlDoc, and retrieves the text node from the first <book> element, replacing all nodes with a new text node:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { myFunction(xhttp); {} }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("book")[0]; document.getElementById("demo").innerHTML = "Before: " + x.textContent + "<br>"; x.textContent = "hello"; document.getElementById("demo").innerHTML += "After: " + x.textContent; {}