document.getElementById('container').addEventListener('click', (e) => {
const children = [...document.getElementsByClassName('profile')];
}
如何访问每个带有img标签的孩子的子节点?
我想做
children.child.node('img').indexOf(e.target)
<div id="container">
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
</div>
答案 0 :(得分:1)
不需要数组操作,可以使用查询字符串.profile > img
选择img
,它们是.profile
的直接子代:
const imgs = [...document.querySelectorAll('.profile > img')];
console.log(imgs.length);
<div id="container">
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
</div>
答案 1 :(得分:0)
使用此选择器#container .profile img
避免选择不需要的元素。
Array.from(document.querySelectorAll('#container .profile > img')).forEach(img => console.log(img));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<div id="container">
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
<div class="profile">
<img src="" />
</div>
</div>
<!-- This is an additionall container -->
<div id="container2">
<div class="profile">
<img src="" />
</div>
</div>