Wednesday, May 20, 2009

Resolving inconsistent behaviour of createElement in Javascript


In my previous post, we have seen how to dynamically create and add HTML elements such textbox using javascript.

The HTML elements can be created using two ways.
One way is, specifying all the attributes at a time while creating the element as below.

var textnode1=
document.createElement("<input id='partName' name='partName[]' type='hidden' />");


The another way is, we can add attributes one by one once after creating an empty element as below.



var textnode1=document.createElement("input");
textnode1.type="hidden";
textnode1.name="partName[]";
textnode1.id="partName";


But it seems IE (Internet Explorer) is behaving inconsistently for both these methods. (i-e First way will work sometimes and the second way will work sometimes).

So we can use try&catch to resolve this issue.

(i-e) We will first try with first way, and if it throws any error then we will go with second way.

Now the final code will look like below,



try {
var textnode1=
document.createElement("<input id='partName' name='partName[]' type='hidden' />");
}
catch(error)
{

var textnode1=document.createElement("input");
textnode1.type="hidden";
textnode1.name="partName[]";
textnode1.id="partName";
}


More Articles...

No comments:

Search This Blog