tags:

views:

1479

answers:

4

Hi

I am creating this JS function that creates an element The function takes two parameters strName and objAttributes

function createElement( strName, objAttributes )
{
  var elem = document.createElement(strName);

  for ( var i in objAttributes )
    elem.setAttribute(i, objAttributes[i]);

  return elem;
}

This works fine in Fx, but not in MSIE I know that the setAttibute method is buggy and the proposed workaround is

elem.attr = 'val';

But right now I have no idea how to write this inside my loop.

I have tried both elem.style and elem['style'] but none of them works.

Can anyone give me some advice,

thanks in advance

t

+3  A: 

Use elem[i].

function createElement( strName, objAttributes )
{
  var elem = document.createElement(strName);

  for ( var i in objAttributes )
      elem[i] = objAttributes[i];

  return elem;
}
strager
yes you are right. Thanks!Now I just have to treat some html attributes like style.
A: 

You can't just swap setting properties and setAttribute.

You have to be careful with setting properties on an element in place of using setAttribute. Style properties and event handlers need to be carefully written, and those attributes that used to be minimized in html (disabled, multiple, readonly) have browser specific valid values.

Also, if you set element.class="mynewclass", you'll get an error, because class is a reserved javascript word, though it is perfectly safe to use it as a string in a setAttribute assignment. THe property name is '.className', and the proper name for a label's 'for' attribute is 'htmlFor'.

kennebec
+1  A: 

Let jQuery handle the cross-browser nonsense...

 $(elem).attr(i, objAttributes[i]);
Josh Stodola
A: 

I've tried handling className and it works, but how can I change the 'type' attribute for an INPUT tag? What I wanna do is to change an input from type="text" to type="password" over IE. I have it working over FireFox though.

Thanks!

Arthur