javascript - "HTML attribute"与 "property of the DOM element"

标签 javascript html dom

<分区>

我对“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 属性。

有时两者之间的关联更为复杂;对一个的更改可能会影响另一个,但不是直接的一对一映射。

关于javascript - "HTML attribute"与 "property of the DOM element",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39322442/

相关文章:

javascript - 混合 PC/平板电脑网站

javascript - 尝试使用 javascript 访问 <a> 的 rel 属性

cordova - 选择下拉 Ionic 不显示文本

javascript - 如何在不使用 tabindex 的情况下在跳转时跳过项目?

javascript - 从右键单击的段落中获取 id 属性

JavaScript 访问父元素

html - 修复了键盘进入屏幕时移动浏览器中的元素问题

javascript - jQuery - 如何找出复选框何时以编程方式更改?

javascript - 在 iOS 中是否存在用于退出 "select scroller"接口(interface)的 vendor 特定事件?

javascript - 为什么这个点击事件失败