Difference between innerText, innerHTML and value?
Unlike innerText
, though, innerHTML
lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText
retrieves and sets the content of the tag as plain text, whereas innerHTML
retrieves and sets the content in HTML format.
innerText vs innerHTML vs label vs text vs textContent vs outerText
From MDN:
Internet Explorer introduced element.innerText. The intention is pretty much the same [as textContent] with a couple of differences:
Note that while textContent gets the content of all elements, including
<script>
and<style>
elements, the mostly equivalent IE-specific property, innerText, does not.innerText is also aware of style and will not return the text of hidden elements, whereas textContent will.
As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
So innerText
will not include text that is hidden by CSS, but textContent
will.
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
In case you missed that, let me repeat it more clearly: Do not use .innerHTML
unless you specifically intend to insert HTML within an element and have taken the necessary precautions to ensure that the HTML you are inserting cannot contain malicious content. If you only want to insert text, use .textContent
or if you need to support IE8 and earlier, use feature detection to switch off between .textContent
and .innerText
.
A main reason that there are so many different properties is that different browsers originally had different names for these properties, and there still isn't complete cross-browser support for all of them. If you are using jQuery, you should stick to .text()
since that is designed to smooth out cross-browser differences.*
For some of the others: outerHTML
is basically the same as innerHTML
, except that it includes the start and end tags of the element it belongs to. I can't seem to find much description of outerText
at all. I think that is probably an obscure legacy property and should be avoided.
innerText/textContent vs. retrieving each text node
It's all about endlines and whitespace - browsers are very inconsistent in this regard, especially so in Internet Explorer. Doing the traversal is a sure-fire way to get identical results in all browsers.
Why do innerHTML and textContent give different results?
Problem -
- a3[2][0][1]; returns undefined, because there's no such element. innerHTML shows undefined but textContent treats undefined as an empty string
const o = document.getElementById('1');
const s = document.getElementById('2');
o.textContent = undefined;
s.innerHTML = undefined;
console.log(typeof o.textContent);
// this means undefined is treated as an empty string
<div id="1"></div>
<div id="2"></div>
Is there any major difference between innerHTML and using createTextNode to fill a span?
Of course. createTextNode
will escape any strings and show them as they are, while innerHTML
could render html-like strings into a DOM. If you don't want that (unless you are sure the text contains no unescaped tags, e.g. when assigning a literal directly), you can use textContent
(or innerText
for IE).
Yet I'd recommend createTextNode
, because all browsers support it equally without any quirks.
comparing innerText/textContent with a value inside a variable
The variable isn't what you've defined it in node's scope, as evaluate runs in the browser's scope. You need to pass the variable to evaluate like below
.evaluate((____size) => {
var correctSize = document.getElementsByTagName('button');
for (var i = 0; i < correctSize.length; i++) {
if (correctSize[i].textContent.indexOf(____size) > -1) correctSize[i].id = 'thisone';
}
}, (____size))
then it works
Assuming you named the variable ____size...
textContent Vs. innerText Cross Browser solution
Re: your edit, not quite. The way to access methods or properties on an object (eg a DOM element) is to use dot notation if you have the name itself, or square brackets in case of variables/expressions (also works with strings, as in obj["propName"]
, which is equivalent to obj.propName
). You can also just test the property against one element and use that from there on:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
var txtProp = ("innerText" in brand[i]) ? "innerText" : "textContent"; //added string quotes as per comments
prd.brand = brand[i][txtProp];
prd.name = name[i][txtProp];
prd.price = price[i][txtProp];
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
Regarding the line:
var txtProp = (innerText in brand[i]) ? innerText : textContent;
The in
keyword checks an object to access the property (syntax: var property in object
). As for the question notation (I made an error earlier, using ||
, the correct thing to use was a :
),
var myVar = (prop in object) ? object[prop] : false;
As an expression, it basically evaluates the stuff before the ?
, and if it's true, returns the expression before the :
, else the one after. So the above is the same as / a shorthand for:
if(prop in object){
var myVar = object[prop];
}
else{
var myVar = false;
}
Since you are checking between two properties only and wanting to assign one or the other, the shortest way would indeed be:
var txtProp = brand[i].innerText || brand[i].textContent;
It would basically test the first property, and if it were false or undefined, it would use the second one. The only reason I (pedantically) avoid using this is because the first test of a || b
would fail even if a
existed but just had a value of 0
, or an empty string (""
), or was set to null
.
nodeValue vs innerHTML and textContent. How to choose?
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.
Related Topics
Comparing Arrays of Objects in JavaScript
How to Add Months to a Date in JavaScript
How to Implement Routereusestrategy Shoulddetach for Specific Routes in Angular 2
Jquery.Parsejson Single Quote VS Double Quote
Html5 Check If Audio Is Playing
How to Find the Width of a Div Using Vanilla JavaScript
Programmatically Play Video with Sound on Safari and Mobile Chrome
Passing a Variable from Node.Js to HTML
Split a String by Commas But Ignore Commas Within Double-Quotes Using JavaScript
How to Mock an Es6 Module Import Using Jest
How to Determine Which Submit Button Was Pressed, Form Onsubmit Event, Without Jquery
How to Load Images Dynamically (Or Lazily) When Users Scrolls Them into View