nodeValue vs innerHTML and textContent. How to choose? [duplicate]
Solution 1:
Differences between textContent/innerText/innerHTML on MDN.
And a Stackoverflow answer about innerText/nodeValue.
Summary
- innerHTML parses content as HTML, so it takes longer.
- nodeValue uses straight text, does not parse HTML, and is faster.
- textContent uses straight text, does not parse HTML, and is faster.
- 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.
Solution 2:
.textContent
outputs text/plain
while .innerHTML
outputs text/html
.
Quick example:
var example = document.getElementById('exampleId');
example.textContent = '<a href="https://google.com">google</a>';
output: <a href="http://google.com">google</a>
example.innerHTML = '<a href="https://google.com">google</a>';
output: google
You can see from the first example that output of type text/plain
is not parsed by the browser and results in the full content displaying. Output of the type text/html
tells the browser to parse it before displaying it.
MDN innerHTML, MDN textContent, MDN nodeValue