Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  194] [ 1]  / answers: 1 / hits: 92156  / 11 Years ago, thu, january 23, 2014, 12:00:00

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?


More From » dom

 Answers
164

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.


[#72985] Wednesday, January 22, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marissatinao

Total Points: 447
Total Questions: 90
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;