获取包含特定标记的节点的子代-JavaScript

时间:2019-02-27 02:28:10

标签: javascript

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>

2 个答案:

答案 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>