dom - JavaScript setAttribute alternative - Stack Overflow

I am creating this JS function that creates an elementThe function takes two parameters strName and ob

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

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

Share Improve this question edited Mar 28, 2009 at 1:31 Scott Evernden 40k15 gold badges80 silver badges84 bronze badges asked Mar 28, 2009 at 0:58 ThomasThomas
Add a ment  | 

3 Answers 3

Reset to default 6

Use elem[i].

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

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

  return elem;
}

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'.

Let jQuery handle the cross-browser nonsense...

 $(elem).attr(i, objAttributes[i]);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744043396a4548730.html

相关推荐

  • dom - JavaScript setAttribute alternative - Stack Overflow

    I am creating this JS function that creates an elementThe function takes two parameters strName and ob

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信