Adding New Elements

With JavaScript, you are not limited to manipulating the elements and objects supplied to a document in its HTML. In fact, you can create objects at will by inserting them into the DOM.

For example, suppose you need a new <div> element. Example 20-8 shows one way you can add it to the web page.

Example 20-8. Inserting an element into the DOM
<html>
    <head>
        <title>Adding Elements</title>
        <script src='OSC.js'></script>
    </head>
    <body>
        This is a document with only this text in it.<br /><br />

        <script>
            alert('Click OK to add an element')

            newdiv    = document.createElement('div')
            newdiv.id = 'NewDiv'
            document.body.appendChild(newdiv)

            S(newdiv).border = 'solid 1px red'
            S(newdiv).width  = '100px'
            S(newdiv).height = '100px'
            newdiv.innerHTML = "I'm a new object inserted in the DOM"
            tmp              = newdiv.offsetTop

            alert('Click OK to remove the element')
            newdiv.parentNode.removeChild(newdiv)
        </script>
    </body>
</html>

First the new element is created with createElement, then the appendChild function is called and the element gets inserted into the DOM. After this, various properties are assigned to the element, including some text for its inner HTML. And then, to make sure the new element is instantly revealed, its offsetTop property is read into the throwaway variable tmp. This forces a DOM refresh and makes the element display in any browser that might otherwise delay before doing so—particularly Internet Explorer. Figure 20-3 shows the result.

Figure 20-3. Inserting a new element into the ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd 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.