按照我的代码:
HTML:
<ul id="ul_o">
<li>v1</li>
<li>v2</li>
</ul>
JS:
console.log(document.getElementById("ul_o").getElementsByClassName("LI").length);
为什么控制台中的数字是 0 而不是 2?
最佳答案
给出 - document.getElementById("ul_o").getElementsByTagName("li").length
要获得更广泛的答案以确保 dom
已准备好被 JS
访问和更新,我们可以使用 onreadystatechange事件类似于 html5 -
<html>
<head>
<title>Test</title>
</head>
<body>
<ul id="ul_o">
<li>v1</li>
<li>v2</li>
<li>v3</li>
</ul>
<script type='text/javascript'>
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
document.body.innerHTML = '<h4><code>ul</code> with <i>ul_o</i> has '+document.getElementById("ul_o").getElementsByTagName("li").length +' <code>li</code> Tags</h4>';
}
}
</script>
</body>
</html>
关于javascript - 使用 javascript 检查 <ul> 中有多少 <li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040825/