Replacing innerHTML and innerText with the DOM
Replacing innerHTML and innerText with the DOM
Internet Explorer 4.0 introduced the DHTML properties innerHTML and innerText,
which let you replace an element’s content dynamically. The difference is that innerHTML
works with elements and lets you insert entire pieces of HTML code, while innerText handles only text content.
InnerHTML and innerText are still around in browsers from the Internet Explorer family
today, but I wouldn’t recommend using them. With widespread implementation of the
DOM
we have a generally accepted interface that lets us move away from the proprietary inner properties.
Let’s skip the theorizing and get straight to the point.
The DOM defines, on the Document
object, the createElement method, which lets us
create elements of a specified type. If we want to create a div element, for example, we use this
construction.
var newElement = document.createElement("div");This code creates an HTMLDivElement, though that’s just a detail. The
new element isn’t yet part of the document. To attach it to the document, use
appendChild, defined by the Node interface. Let’s see how attaching the new element works with another
simple example.
- Bar
- Acme
var newElement = document.createElement("div");
/*získáme referenci na uzel, ke kterému chceme připojit nový element*/
var refNode = document.getElementById("foo");
refNode.appendChild(newElement);//provedeme připojeníCreating the missing text content, without which the element wouldn’t be much use, also shows how to replace
innerText. Text content
is created in a similar way to the elements above, using the createTextNode method, again defined by Document.
- Bar
- Acme
var newElement = document.createElement("div");
var newText = document.createTextNode("bar.acme.com");
newElement.appendChild(newText);
var refNode = document.getElementById("foo");
refNode.appendChild(newElement);The example shows that the DOM takes more work than innerHTML and innerText, but it does ensure
the code works in all browsers that support the DOM. On the other hand, innerHTML has been
implemented in Mozilla, for instance, even though it isn’t part of the DOM.
Related articles
- (Dagblog 4.1.2004) Getting to know the DOM I
- (Dagblog 5.1.2004) Getting to know the DOM II — Document structure and object model
- (Dagblog 12.1.2004) Getting to know the DOM III — Modules and levels
- (Dagblog 29.1.2004) Getting to know the DOM IV — Walking the document
- (Dagblog 24.2.2004) Getting to know the DOM V — Walking the document, part two
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio