JS DOM: textContent, innerHTML, innerText, nodeValue
What is the difference between textContent, innerHTML, innerText, nodeValue?
innerHTML
innerHTML
is meant to be HTML code.- Text is not ampersand encoded.
// change text content of first p tag document.getElementsByTagName("p")[0].innerHTML = "<b>water</b>"; // the word is shown as bold
textContent
- It represent to raw text of an element.
- Text is automatically ampersand encoded.
// change text content of first p tag document.getElementsByTagName("p")[0].textContent = "<b>water</b>"; // bold tag is rendered as text as is
innerText
- It represent to raw text of visible part of an element. (CSS: Hide Element (visibility) )
- Text is automatically ampersand encoded.
// change text content of first p tag document.getElementsByTagName("p")[0].innerText = "<b>water</b>"; // bold tag is rendered as text as is
nodeValue
nodeValue
is for setting content of text node only. γsee get Node Name (Element Tag Name), Node Type, Node Valueγ- It is particularly useful when working with XML, such as SVG. γsee Practical SVG Tutorialγ
The most compatible and standard way of setting text content is first to get the element's content as a text node, then set nodeValue
, like this:
node.firstChild.nodeValue = text
But, if a element's content is empty, it doesn't have any child (thus no text node), so you need to check if element has firstChild
first.
// change a element's text content, for xml or html // add a text content xtext to an element xel // Version: 2022-08-21 const f_addTextNode = ((xel, xtext) => { if (xel.firstChild) { xel.firstChild.nodeValue = xtext; } else { xel.appendChild(document.createTextNode(xtext)); } }); f_addTextNode(document.getElementsByTagName("p")[0], "good");
History
nodeValue
is in web standard since 1990s.innerHTML
is originally from Microsoft Internet Explorer. Is made into standard, supported by all browsers back to 2010.innerText
is originally from Microsoft Internet Explorer, but is now in html spec. It's not supported by Firefox as of 2015-03-13.textContent
is in standard's spec around 2011, and is supported by browsers since about 2013.