Adding to the DOM Tree



JSEarlier in the week we looked at the original way to update your document via JavaScript. But those methods (primarily write() and writeln()) had significant drawbacks, primarily the inability to update a document after it had finished loading. The introudction of the DOM changed all that.



Creating Elements


The first thing you need to do is to create the elements you want to add to the page. If you are adding text, you use createTextNode(). If you are creating an HTML tag, you should use the createElement() method. createTextNode() takes as a parameter the text you would like to add. The createElement() method takes a single parameter that is the name of the tag you are creating. Although HTML is case sensitive, you should use lowercase for your tag names. There are versions of Safari that where createElement() will not work with uppercase tag names. See the examples below.
var pTag = document.createElement('p');
var textNode = document.createTextNode("This is a test");


Adding Elements to the DOM


Now that we have these elements and tag nodes-how do we add them to our page? By using the appendChild() method.
<html>
    <body>
        <div id="testDiv"></div>
        <script>
            var pTag = document.createElement("p");
            var textNode = document.createTextNode("This is a test");

            var divTag = document.getElementById("testDiv");
            pTag.appendChild(textNode);
            divTag.appendChild(pTag);
        </script>
    </body>
</html>

In the above example, we add the textNode to the 'p' tag. We also use document.getElementById() to retrieve the 'div' tag on the page, and then append our 'p' tag to it.


No comments :