Chapter 12. Creating and Removing Elements and Attributes
12.0. Introduction
The existing Document Object Models provide a plethora of methods you can use to create new web document elements. Most of the methods I use in this chapter and in the following chapters are from the DOM Levels 1 and 2 and, since most of the examples in this chapter are specific to HTML or XHTML documents, the methods and objects described inherit functionality from both Core and HTML DOM specifications.
There is one older property, innerHTML, from the nonstandard DOM Level 0,
that I’ll also demonstrate, primarily because it’s so popular, and also
because of new support in HTML5.
Most of the methods and associated properties are available with all of the modern browsers. I’ll make a note where a method or property isn’t supported by one or more browsers.
See Also
See the Introduction to Chapter 11, for a more in-depth look at the Document Object Model and the DOM levels.
12.1. Using innerHTML: A Quick and Easy Approach to Adding Content
Problem
You want to add a couple of paragraphs with text to a div element, and you want to do so quickly and
easily.
Solution
Use the innerHTML property to
overwrite an element’s existing contents, with new material:
var div = document.getElementById("target");
div.innerHTML = "<p>This is a paragraph</p><p>This is a second</p>";Discussion
The innerHTML property has been around for a very long time, and is part of what is known as DOM Level 0—the first de facto API developed by the browser ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access