Chapter 14. Adding HTML with JavaScript

The Document Object Model (DOM) is about much more than finding particular elements in the page. Remember that JavaScript's purpose in web development is to provide a higher level of interactivity with the user, and there will be times when you want to add elements dynamically to the web page according to the user's input.

The DOM allows you to create new HTML elements and add them to the page on-the-fly. You can do this in one of two ways: with creation methods provided by the DOM standard, and with the innerHTML property. The results of these two methods look identical on the surface, but which one you should choose depends on the final result you want to achieve.

DOM CREATION METHODS

The document object is an instance of the DOM data type called Document. Its members provide many useful methods allowing you to create other DOM objects like elements and text nodes. Here you'll look at how to create these types of objects, starting with HTML elements.

Before you begin, however, the following code shows the HTML document this lesson works with:

<html>
<head>
    <title>Sample Page</title>
</head>
<body>
    <script type="text/javascript">

    </script>
</body>
</html>

It is a simple web page with a sole <script/> element in the body. The script covered in this lesson will go inside the <script/> element.

Creating Elements

The Document data type specifies a method called createElement(). It accepts one argument, a string containing the tag name of the element ...

Get JavaScript® 24-Hour Trainer 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.