最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - JavaScript setAttribute alternative - Stack Overflow

programmeradmin1浏览0评论

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]);
发布评论

评论列表(0)

  1. 暂无评论