如何使用 JavaScript 向 HTML 元素添加/更新属性?

我试图找到一种方法,可以使用 JavaScript 添加/更新属性。我知道我可以做到这一点与 setAttribute()的功能,但这不工作在 IE。

329187 次浏览

你想对这个属性做什么? 它是一个 html 属性还是你自己的属性?

大多数情况下,您可以简单地将其称为属性: 想要为元素设置标题吗?element.title = "foo"可以。

对于您自己的定制 JS 属性,DOM 是自然可扩展的(aka expdo = true) ,其简单结果是您可以执行 element.myCustomFlag = foo并随后毫无问题地读取它。

强制性 JQuery 解决方案。查找并将 title属性设置为 foo。注意,这里只选择了一个元素,因为我是通过 id 来完成的,但是您可以通过更改选择器轻松地在集合上设置相同的属性。

$('#element').attr( 'title', 'foo' );

您可以阅读 给你,了解许多不同浏览器(包括 IE)中属性的行为。

element.setAttribute()应该可以做到这一点,即使在 IE 中。你尝试过吗? 如果它不工作,那么也许 element.attributeName = 'value'可能有用。

如果你想要完全兼容的话,看似简单的事情实际上是很棘手的。

var e = document.createElement('div');

假设要添加“ div1”的 id。

e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).

But there are contingencies, of course. Will not work in IE prior to 8:e.attributes['style'] Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.