调用getElementByTagName时的意外元素



我是javascript的新手,不明白为什么当我调用getElementByTagName()时在集合中循环时,我会在标签后得到一个函数作为输出;

我是一个英语新手,所以这里有一个片段来帮你弄清楚我的问题和我的问题。

function div1ParaElems() {
const div1 = document.getElementById("div1");
const div1Paras = div1.getElementsByTagName("div");
const num = div1Paras.length;
alert(`There are ${num} paragraph in #div1`);
let out = document.getElementById("output");
for (let i in div1Paras){
out.innerHTML += div1Paras[i] + "<br>";
div1Paras[i].addEventListener("click",alertMe);
}
}
function alertMe(e){
alert(e.target.innerHTML);
}
*{
box-sizing: border-box;
}
.flexTest{
display: flex;
flex: auto;
flex-wrap: wrap;
align-items: flex-start;
/*justify-content: space-around;*/
/*justify-content: space-between;*/
border:1px solid #D2D2D2;
background-color: burlywood;
}
.flexTest div{
background-color: antiquewhite;
padding:10px;
margin:10px;
display: flex;
flex: content;
border:1px solid #D2D2D2;
}
<body onLoad="div1ParaElems()">
<div id="div1" class="flexTest">
<div>
Tatactic - Nicolas 1
</div>
<div>
Tatactic - Nicolas 2
</div>
<div>
Tatactic - Nicolas 3
</div>
<div>
Tatactic - Nicolas 4
</div>
<div>
Tatactic - Nicolas 5
</div>
<div>
Tatactic - Nicolas 6
</div>
<div>
Tatactic - Nicolas 7
</div>
<div>
Tatactic - Nicolas 8
</div>
</div>
<div id="output"></div>
</body>

为什么我得到function item() { [native code] }在我的输出结束,即使它不是一个div元素?

提前感谢您的时间和耐心!

输出包含9个元素,而不是预期的8个。

[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
function item() { [native code] }

这是因为您正在使用for..in,它将div1Paras视为对象,迭代其属性(包括length,item方法等)。你可能想用for..of代替。

for (let div of div1Paras) {
out.innerHTML += div + "<br>";
div.addEventListener("click", alertMe);
}

相关内容

最新更新