views:

45

answers:

2

Hi,

I've been using innerHTML and innerText for a while to change elements and text on web pages and I've just discovered that they are not W3C standard.

I've now found that innerHTML can be replaced with createElement, setAttribute and a few others but what is the best method for changing text inside an element?

I found a textContent as well but is there a standard way and is it widly implemented across older browsers?

+1  A: 

I think you can't go wrong by using whatever your javascript library offers for changing text (innerHtml for jQuery). After all one of the the main reasons for using such a library is having a platform that abstracts from different browser implementations.

Adrian Grigore
What if he's not using a library? Also, jQuery doesn't offer "innerHtml" for changing text. The *text()* method should be used for that, *html()* is for setting HTML.
Andy E
@Andy E: You are right, he might not use any. On the other hand, using javascript without any library is really painful for medium to large projects, at least if you want your website to work with all major browsers. I wouldn't want to do it.
Adrian Grigore
@Adrian: and neither would I - I have in the past but it only makes sense to use a library now :-) For small, simple pages and scripts, I stick to vanilla JS though.
Andy E
+3  A: 

textContent isn't implemented in IE8 and lower. You can use createTextNode() similar to how you would use createElement(). However, I often use discovery techniques to find out which property I need to use and keep a reference to it:

// You can use a shorter variable name if you want
var innerTextOrTextContent = "textContent" in document.body 
                               ? "textContent" : "innerText";

// Set an element's text:
myElement[innerTextOrTextContent] = "Added using: "+innerTextOrTextContent;

The createTextNode() example:

var tNode = document.createTextNode("Added using createTextNode()");
myElement.appendChild(tNode);

Something I often forget about, you can also directly set a text node's value, if you can get a reference to it:

// childNodes[0] is a text node:
myElement.childNodes[0].nodeValue = "Added using nodeValue";

Example - http://jsfiddle.net/BxPaG/.

Andy E
Nice, I didn't know about the `createTextNode` method.Would you say it would be silly to create a new `<span>` element with `createElement` and apply attributes and content and replace the old `<span>` element with 'replaceChild' instead of simply using `innerText` or 'textContent'?
Ryan
@Ryan: yes, that wouldn't make much sense given that there are other options available. You can use *replaceChild()* instead of *appendChild()* to replace the current text node. Also, if you can get a reference to a text node, you can change it's value directly using *nodeValue* - see my update.
Andy E
@Andy E: Ok, thanks :)
Ryan