Tuesday, May 20, 2008

Creating Elements


Description

The purpose of this article is demonstrate how to dynamically create elements and append them to the document.



createElement

The createElement method creates a new element node with the specified name tag. This method returns a reference to the created element.

reference = document.createElement(tagName);

The method takes a single string parameter (the name of the element to be created).

var pnl = document.createElement("div");

The reference returned by createElement is a node object referenced by variable "pnl". However, the div element has not yet been added to the document, it has only been created. Lets go ahead and set some properties before we add it to the document.

var pnl = document.createElement("div");
pnl.style.background = "#fff";
pnl.style.width = "100%";
pnl.style.height = "20px";

Lastly, adding out element to the document:

document.appendChild(pnl);

Example

Replicate the HTML code you see below using DOM scripting.

<table>
<tr>
<td></td>
</tr>
</table>

Solution:

var tbl = document.createElement("table");
var tr = document.createElement("tr");
var td = document.createElement("td");
tr.appendChild(td);
tbl.appendChild(tr);
document.appendChild(tbl);

1 comments:

CodeApedia said...

Just a quick note. This article is intended to introduce the createElement method and how it is defined within the DOM core. Do not assume that everything will work perfectly in every browser. You should always test your functions in multiple browsers before publishing any web content. In the example above, there is a well-known bug with Internet Explorer. This can be easily remedied by appending the rows to a "tbody" element. Again, discussions of cross browser compatibility is beyond the scope of simply introducing the DOM methods and how they are defined.

 

blogger templates | Make Money Online