开发者

Proper way to change text and elements on a page with JavaScript

I've been using innerHTML and innerText for a while to change elements and text on web p开发者_如何学编程ages 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?


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/.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜