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
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
Figure 20-3. Inserting a new element into the ...