innerHTML

When compared to the surgical precision of other DOM methods and properties, innerHTML has all the subtlety of a sledgehammer. Originally part of the Internet Explorer DOM (i.e., not part of the W3C DOM), but now widely supported, this element property can be used to get and set all of the markup and content within the targeted element. The main problem with using innerHTML to get content is that the collected content is treated as though it is a string, so it’s pretty much only good for moving large amounts of content from one place to another.

Using the example above, you could collect all of the contents of the content div by writing:

var contents = document.getElementById( 'content' ).innerHTML;

Similarly, you could replace contents of the div by setting its innerHTML equal to a string of text that includes HTML:

var contents = 'This is a <em>new</em> sentence.';
document.getElementById( 'content' ).innerHTML = contents;

It is also possible to append content to an element using innerHTML:

var div = document.getElementById( 'content' ).innerHTML;
div.innerHTML += '<p>This is a paragraph added using innerHTML.</p>';

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.