I'm using plain js to alter the inner text of a label element, and I wasn't sure on what grounds I should use innerHTML or nodeValue or textContent. I don't need to create a new node or change the HTML elements or anything — just replace the text. Here's an example of the code:
var myLabel = document.getElementById("#someLabel");
myLabel.innerHTML = "Some new label text!"; // this works
myLabel.firstChild.nodeValue = "Some new label text!"; // this also works.
myLabel.textContent = "Some new label text!"; // this also works.
I looked through the jQuery source, and it uses nodeValue exactly one time but innerHTML and textContent several times. Then I found this jsperf test that indicates the firstChild.nodeValue is significantly faster. At least that's what I interpret it to mean.
If firstChild.nodeValue is so much faster, what's the catch? Is it not widely supported? Is there some other issue?
nodeValue
at all. In a situation like in this fiddle, which illustrates the practical differences betweeninnerHTML
,innerText
,textContent
andnodeValue
, usingchildNodes[0].nodeValue
is the only way to get just the text content of the element itself without including any nested elements that it may have - good for getting a label contents without any nested inputs, for example. Take care with closing valid questions, please. – Dandle