Google

Wednesday, November 7, 2007

How to add HTML controls / elements dynamically to a page

How to add HTML controls / elements dynamically to a page ------------------------------------------------------------------------------------------------ Hmm .... now there's a familiar javascript problem. You know what javascript is ... know how it works ... know that you can manipulate controls, but how do you actually add new elements to the page using JS. To revise our principles and beliefs -- The javascript hierarchy looks like this : Document --> HTML --> Body --> Page Elements. The above expression omits one essential fact though - "Controls on a page can be children of other controls on the page". Confused ? Let's look at an example :

<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<div id="myDiv">
<input type="button" id="btn" value="Click Me" />
</div>
</body>
</html>
In the above html, the <input> element with id = "btn", is a CHILD OF the <div> element.Getting the hang of it ??! Let's fudge up things a little bit
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<div id="myDiv">
<input type="button" id="btn" value="Click Me" />
<div id="childDiv">
<h id="childH"> Child </h>
</div>
</div>
</body>
</html>
Again, the hierarchy we have is : Meaning, myDiv element has two children - btn, and childDiv. In turn, childDiv has one child of its own, called childH. Now do you get the hang of it ??!!. If not, look at my earlier post on debugging javascript, and try debugging this piece of HTML script. Pay close attention to the "children" properties of the elements. Please note that the parent-child relationship determines how elements are displayed on the page. In the above case, the button "myBtn" will be shown "inside" the myDiv element's area on screen. Again, the childH element will be shown inside the childDiv area, which in turn falls inside the area for myDiv, which in turn falls in the area for <body> . When an element is child of the <body> element, it is not shown as a part of any other control, because <body> tag stands for the entire browser area. More on this in a later post. All right, now about adding elements dynamically. There are roughly two situations where you would be adding an element to an html page : 1) Adding an element directly to the page's <body>. 2) Adding an element as a child of some other element. Let us look at case # 1 first - Adding an element to the <body> tag. Theoretically, this is the same as the case # 2, with the only difference that the element that you add is a child of the <body> element. First, we need to define an event. An event is (usually) some kind of action that the user will perform on the browser while viewing a web page. The action can be a button click, or moving the mouse or even typing something in a textbox. The reason we're associating an event here is to allow the user to trigger the process of adding a control dynamically. Meaning, the javascript that dynamically adds the controls to the page should be called only when the user performs that action.
<html>
<head>
    <title>Untitled Page</title>
</head>
<body>
    <div id="myDiv">
        <input type="button" id="btn" value="Click Me" />
        <div id="childDiv">
            <h id="childH"> Child </h>
            <input type="button" id="addCtrl" value="Add a new Elt" onclick="var elt = document.getElementById('childDiv');
var newElt = document.createElement('LABEL');
newElt.innerText = 'I was just added';
elt.appendChild(newElt);" />
        </div>
    </div>
</body>
</html>
Ok, so here we go. First, look at the line beginning with "onclick". This is like telling the browser, "Whenever the user does a click on this button (that is, clicks the button), run this piece of javascript". Simple, huh. And lets dissect the javascript -- var elt = document.getElementById('childDiv'); You should be familiar with this. If not, look at my post on javascript debugging. This is fetching the object for childDiv, and assigning to the variable 'elt'. Next up, var newElt = document.createElement('LABEL'); Here, we are creating a new element of type 'label'. Usually, when you need to display some plain text on the screen, we use this type of element. The new element is now stored in the 'newElt' variable. Next, newElt.innerText = 'I was just added'; This is basically setting a property for that control, so that when the object is shown on the browser, it writes "I was just added" on screen, and we know that it exists. elt.appendChild(newElt); Now this is the most critical part. We are adding the element we created above using the 'createElement' method, to the element that elt refers to. Meaning, we are adding the newly created element 'newElt' to the 'childDiv' element. Once done, the hierarchy would look like this : You can verify this by running the page. Initially you will not see any label text. As soon as you click the button, the text "I was just added" will appear. I would also advise that you look at what is happening by debugging the javascript. In case you are not familiar with debugging javascript, you can refer to my earlier post. Hmm ... that was fun and easy. Next time, we will look at a related problem - dynamically building html tables. Keep learning.

2 comments:

Anonymous said...

when you call .createElement('label');

be sure to use lower case tag names.

Although it will still work in HTML4, in XHTML, this will cause issues.

Besides, it looks very amaturish and reminicent of the old, and bad code samples on MSDN

Swati.Saurabh said...

First of all, thank you for your comments. The post was meant for the amateur learner, and our aim is to gradually advance the reader to more complex topics like OO javascript, ajax etc. Once again, thank you and stay tuned.