I've had a nightmare over the past couple of weeks wondering why my code wasn't working in ie. I've finally realised that it was because I was using textcontent which works fine in firefox. I tried using innertext and it worked fine in ie but stopped working with firefox. Chrome seems to support both. I switched and used innerHTML and it works fine across all three browsers.

My question is what is the different between innerHTML and the other two and is it safe to use?

Recommended Answers

All 3 Replies

The only browser that doesn't support the original innerText property and method is firefox.
It's not IE's fault that someone else took its feature and called it "my invention" by changing its original name. Never mind that it will cause the web to break! Which in return is its exact aim and the reason of renaming your tools in the first place.

Anyhow:
Using the innerHTML as an alternative to innerText was always possible but not always safe. It depends on what you are trying to do. If you are using it as a property or as a method which makes the main difference. Let's exemplify the distinction:

some div content:
"div with a [B]bold[/B] element"
used as properties of the element will return:

div.innerText >> "div with a bold element"
div.innerHTML >> "div with a <b>bold</b> element"

whereas, using them as methods for the same content
"div with a <b>bold</b> element"
will give you a:

div.innerText = "div with a <b>bold</b> element"
>>  "div with a <b>bold</b> element"
div.innerHTML="div with a <b>bold</b> element"
>> "div with a [b]bold[/b] element"

So it is safe to use, as long as the tool you are using, will do what you are aiming to.

thank you for taking time out to answer my question. I was really impressed by your explanation.

...
so, in order to solve possible problems with this I suggest you do some scripting for cross-browser normalization like

var text = document.body.textContent ? "textContent" : "innerText";
// which will enable you to access and modify the text content using:
   oElement[text]; >> "this element plain text content"
// or assign  
   oElement[text] = "this element new plain text"

And of course mark the thread solved.
p.s.:
(Prototyping it, -is currently a no go.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.