我对“HTML 属性”和“DOM 元素的属性”之间的区别感到困惑。来自 this post ,我了解到 getAttribute("class")
返回前者,而 element.className
返回后者。但是,我无法理解以下代码的输出:
var span = document.querySelector("#span");
console.log(span.className + ' ' + span.getAttribute("class"));
span.className = "bar";
console.log(span.className + ' ' + span.getAttribute("class"));
<span id="span" class="foo"><span>
我希望结果是
foo foo
bar foo
因为据我所知,在运行 javascript 时我的 HTML 文件的内容没有被更改。此外,当我更换 span.className = "bar";
符合 span.setAttribute('class', 'bar');
, 结果相同。
我的问题是:“HTML属性”和“DOM元素的属性”有什么区别和关系?
为了进一步混淆问题,HTML5 规范将它们分别称为内容属性和 IDL 属性。
它们有时由相同的名称关联,有时则不同。
在最常见的关联类型中,这两种类型的属性被称为相互“反射(reflect)”,因此当一个发生变化时,另一个也会发生变化。 HTML5 在 Reflecting content attributes in IDL attributes 中对此进行了描述.第一段说:
Some IDL attributes are defined to reflect a particular content
attribute. This means that on getting, the IDL attribute returns the
current value of the content attribute, and on setting, the IDL
attribute changes the value of the content attribute to the given
value.
有时相互反射(reflect)的IDL属性和内容属性有不同的名字。例如,输入的“值”内容属性由 defaultValue 反射(reflect)IDL 属性。
有时两者之间的关联更为复杂;对一个的更改可能会影响另一个,但不是直接的一对一映射。