Showing posts with label DOM element. Show all posts
Showing posts with label DOM element. Show all posts

Friday, June 5, 2009

How to Create DOM Element with Javascript

To create a DOM element with Javascript is very simple, look as the following example you will find it is just a piece of cake.

<script>
function addTR(tableid)
{
var atr=document.createElement('TR');
atr.setAttribute('id','tr4');
document.getElementById(tableid).appendChild(atr);
addTD('tr4');

}
function addTD(trid)
{
var atd=document.createElement('TD');
var atr=document.getElementById(trid);
atd.innerHTML='TD created by JS';
atr.appendChild(atd);
}
function addInputButton(parentId)
{
var abut=document.createElement('INPUT');
abut.setAttribute('type','button');
abut.setAttribute('name','buttybutton');
abut.setAttribute('value','Butty Button');
document.getElementById(parentId).appendChild(abut);
}
function addInput(parentId,type,inputname,inputvalue)
{
var aInput=document.createElement('INPUT');
aInput.setAttribute('type',type);
aInput.setAttribute('name',inputname);
aInput.setAttribute('value',inputvalue);
document.getElementById(parentId).appendChild(aInput);
}
</script>

<table name='t1' id='t1'>
<tr id='tr1'>
<td>
<input type=button onclick="addTR('t1');" value='Add TR'>
<input type=button onclick="addTD('tr2');" value='Add TD'>
<input type=button onclick="addInputButton('butbox');" value='Add Button'>
<input type=button onclick="addInput('butbox','text','textbox1','Wow Dynamic');" value='Add Textbox'>
</td>
</tr>
<tr id='tr2'></tr>
<tr id='tr3'><td>Hello</td></tr>
<tr id='tr5'><td id='butbox'></td></tr>
</table>