SetAttribute on IE6 and firefox

Thursday, May 29, 2008

Say, you want to create an element using javascript with code like

<div class="myClass" onClick="myFunction()">inner HTML</div>
Now, the way to do it in firefox is by simply using javascript setAttribute like this:
<script language="javaScript">
element = document.createElement("div");
 element.appendChild(document.createTextNode("inner HTML"));
 element.setAttribute("class", myClass");
 element.setAttribute("onClick", "myFunction()");
</script>

But on Internet Explorer, that code won't work. It's broken. The class part should be written className on IE, so instead of >element.setAttribute("class", myClass"); it should be >element.setAttribute("className", myClass");, and what if you have many element attributes that you don't know whether they're applied the same way on IE and firefox ? like >style, id, name, on{Change, MouseOver, etc} ?

So far, here's the quick solution to do it, it's only a try catch block actually :
>
<script language="javaScript">
try {
   element = document.createElement("<div class=\"myClass\" onclick=\"myFunction()\">");
   element.appendChild(document.createTextNode("inner HTML"));
 } catch (e) {
   element = document.createElement("div");
 element.appendChild(document.createTextNode("inner HTML"));
 element.setAttribute("class", myClass");
 element.setAttribute("onClick", "myFunction()");
 }
</script>


Quite quick, eh ?

0 comments: