【发布时间】:2021-07-06 00:37:31
【问题描述】:
我不明白为什么对于某些标签,getElementsByTagName 方法返回一个空列表。这是 MWE:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
</head>
<body>
<figure class="figure" id="other figure">
<image src="https://p.bigstockphoto.com/GeFvQkBbSLaMdpKXF1Zv_bigstock-Aerial-View-Of-Blue-Lakes-And--227291596.jpg" width="100%" style="max-height: 70vh"></image>
<figcaption>I am a figcaption.</figcaption>
</figure>
<float class="figure" id="my figure">
<image src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" width="100%" style="max-height: 70vh"></image>
<caption>I am a caption</caption>
<figcaption>I am a figcaption 2.</figcaption>
<p>1</p>
<p>2</p>
</float>
<script>
console.log(document.getElementsByTagName("float")); // Works fine with this custom tag
console.log(document.getElementsByTagName("figure")); // Works fine
console.log(document.getElementsByTagName("image")); // Fails, returns empty list with NON custom tag
console.log(document.getElementsByTagName("caption")); // Fails, returns empty list
console.log(document.getElementsByTagName("figcaption")); // Works fine
console.log(document.getElementsByTagName("p")); // Works fine
</script>
</body>
</html>
以防之前 sn-p 的行为依赖于浏览器,这是我的截图格式的结果:
【问题讨论】:
-
对于
<image>这是因为 HTML 解析器会自动将这些转换为实际的 HTMLImageElement<img>。对于<caption>,它应该在<table>中才有效。否则它会被删除。 -
请注意,您显示的 HTML 无效。 HTML 没有
float元素。如果要创建自定义元素,这些元素需要符合自定义元素要求才能有效,其中最低要求是元素的标记名必须至少包含两个用破折号分隔的单词。 -
感谢您的评论@connexo。还必须指出,我在这里使用的“无效”元素比标准的
caption和image元素具有更可预测和更直观的行为。事实上,我对caption元素的解决方案是发明我自己的floatcaption标签,而且效果很好。 -
无效的 HTML 从不是一个选项。论点 works fine 不相关。编写依赖于系统容错或在某个时间点观察到的未指定行为的代码是非常糟糕的开发。
标签: javascript html getelementsbytagname