dagblog.
← Archive

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

Medium version

Related articles

Related CZ Podcast episodes