我正在尝试记录 html 文档中具有 id
“para”的元素数量,这里是到目前为止的代码
window.addEventListener("load",init);
function init(){
var b = document.getElementById("para");
console.log(b);
}
到目前为止,它只会记录元素本身,而不记录 html 文档中的元素数量
最佳答案
var b = document.getElementById("para");
注意此类中的单数,它仅返回单个元素(或 null)。
如果您的文档格式良好,则只会有一个 ID 为 para
的元素。这是将 ID 与类分开的原因之一。
您有两种解决方案。
- 不要使用 ID,而使用 class 或 data-* 属性
- 使用
document.querySelectorAll("#para")
在这两者中,我建议修复您的 HTML。
引用评论的演示代码
var list = document.querySelectorAll("#test-span");
console.log(list.length);
<span id="test-span">1</span>
<span id="test-span">1</span>
<span id="test-span">1</span>
关于javascript - 如何将特定 DOM 元素的编号记录到控制台中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37493252/