Cover by Robin Nixon

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required