我想要展示的是,HTMLCollection是一个活动列表,NodeList是静态的。为此,我将页面上的div总数存储在每个变量中(g表示HTML,q表示Node),即1。我用GetElementBy.和querySelector....respectively。
console.log(q.length) // 1
console.log(g.length) // 1
然后使用JS创建一个新的div并将其附加到页面中。总人数现在2人。
console.log(q.length) // 1
console.log(g.length) // 2
但是,在控制台中,所有这些操作都很好,但我无法正确显示g.length。我收到了一个TypeError。我不太明白g.length怎么可能是空的
ScreenShot:

带有JS的index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function newElement() {
newDiv = document.createElement('div')
newDiv.innerHTML = 'Div 2'
document.getElementById('wrapper').appendChild(newDiv);
}
function updateStats() {
document.getElementById('queryA').innerHTML = q;
document.getElementById('getA').innerHTML = g;
document.getElementById('queryAL').innerHTML = q.length;
document.getElementById('getAL').innerHTML = g.length;
}
</script>
</head>
<body>
<button onClick="newElement();">Add Element</button>
<button onClick="updateStats();">Update Stats</button>
<header id="wrapper">
<div>
Div 1
</div>
</header>
<h3>querySelector Before</h3>
<p>Type:<span id="queryB"></span></p>
<p>Length:<span id="queryBL"></span></p>
<h3>After</h3>
<p>Type:<span id="queryA"></span></p>
<p>Length:<span id="queryAL"></span></p>
<hr>
<h3>getElementByTagName Before</h3>
<p>Type:<span id="getB"></span></p>
<p>Length:<span id="getBL"></span></p>
<h3>After</h3>
<p>Type:<span id="getA"></span></p>
<p>Length:<span id="getAl"></span></p>
<script>
q = document.querySelectorAll('div')
g = document.getElementsByTagName('div')
document.getElementById('queryB').innerHTML = q;
document.getElementById('queryBL').innerHTML = q.length;
document.getElementById('getB').innerHTML = g;
document.getElementById('getBL').innerHTML = g.length;
</script>
</body>
</html>我搜索了谷歌,找不到答案,把脚本移到页面底部不起作用。
发布于 2021-07-26 15:01:24
第15行您将得到incorect id:
试试这个:document.getElementById('getAl').innerHTML = g.length;
发布于 2021-07-26 15:00:10
本例中的问题是document.getElementById('getAL')为空,而不是g.length。
https://stackoverflow.com/questions/68531659
复制相似问题