为什么JavaScriptreturnHTML标签中的tagName方法要大写?

Why does tagName method in JavaScript return HTML tags in capital letters?

为什么JavaScriptreturnHTML标签中的tagName方法要大写? HTML 标签应以小写字母书写。

因为那是 how tagName is defined:

The tagName attribute’s getter must return the context object’s HTML-uppercased qualified name.

HTML 标签名称(和属性名称)不区分大小写,但标签名称的规范版本全部大写,无论创建元素的 HTML 是如何编写的:

document.querySelectorAll("div").forEach(function(div) {
  console.log(div.tagName);
});
<div></div>
<DIV></DIV>
<Div></Div>

这非常方便,因为这意味着查看 tagName 的代码如果需要知道是否需要在进行比较之前不必调用 toUpperCase(或 toLowerCase)标签匹配特定的标签名称。例如,if (element.tagName === "DIV") 在 HTML 页中是可靠的。

HTML 的旧版本在 JavaScript 首次创建时使用全部大写的标签名称按照惯例而不是今天的小写字母。为了与旧代码保持向后兼容 tagName() 仍然 returns 全部大写并且一直保持这种状态。

为了完整起见,请注意 tagName:

Returns the tag name of the element on which it's called. For example, if the element is an , its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents).

使用 svg 查看下面的结果:

[...document.querySelectorAll("*")].forEach(function(el){
  console.log(el.tagName);
});
 <svg width="300px" height="300px" 
    xmlns="http://www.w3.org/2000/svg">
    <text x="10" y="50" font-size="30">My SVG</text>
  </svg>