Proprietà textContent dell'XML DOM
Definizione e uso
textContent
Proprietà che restituisce o imposta il testo dell'elemento selezionato.
Quando si restituisce il testo, questa proprietà restituisce il valore di tutti i nodi di testo all'interno del nodo dell'elemento.
Quando si imposta il testo, questa proprietà elimina tutti i nodi figli e li sostituisce con un singolo nodo di testo.
Attenzione:Questa proprietà non funziona in Internet Explorer 9 (ritorna undefined).
Suggerimento:Per impostare e restituire il valore di testo del nodo, utilizzare l'attributo nodeValue del nodo di testo.
Sintassi
Restituire il testo:
elementNode.textContent
Impostare il testo:
elementNode.textContent=string
Esempio
Esempio 1
Il seguente codice carica "books.xml" nel xmlDoc e ottiene il nodo di testo del primo elemento <title>:
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 = "Nodi di testo: " + x.textContent; {}
Esempio 2
Il seguente codice carica "books.xml" nel xmlDoc e ottiene il nodo di testo del primo elemento <book>, sostituendo tutti i nodi con un nuovo nodo di testo:
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; {}