Saturday, March 2, 2019

javascript - nodeValue vs innerHTML and textContent. How to choose?



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?


Answer



Differences between textContent/innerText/innerHTML on MDN.



And a Stackoverflow answer about innerText/nodeValue.




Summary




  1. innerHTML parses content as HTML, so it takes longer.

  2. nodeValue uses straight text, does not parse HTML, and is faster.

  3. textContent uses straight text, does not parse HTML, and is faster.

  4. innerText Takes styles into consideration. It won't get hidden text for instance.



innerText didn't exist in firefox until FireFox 45 according to caniuse but is now supported in all major browsers.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...