【问题标题】:How to select the first number of elements with querySelectorAll如何使用 querySelectorAll 选择第一个元素
【发布时间】:2022-01-04 21:06:34
【问题描述】:

例如,假设我在网页中有 25 个图片

我的问题是:如何选择前 6 个图像,以便将setAttribute 更改为其他内容。

但我不想这样做

document.queryselectorAll('img')[0]
document.queryselectorAll('img')[1]
document.queryselectorAll('img')[2]
document.queryselectorAll('img')[3]
document.queryselectorAll('img')[4]
document.queryselectorAll('img')[5]

我需要一种更简单的方法来编写所有内容 帮助??????

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来自行解决此问题? .querySelectorAll() 使用 CSS 选择器。那将是一种可能的方式...
  • for (let i=0; i < 6; i++) { ...... } 呢?
  • 成功了,谢谢

标签: javascript html dom


【解决方案1】:

为什么不做一个循环?

逻辑

首先我们使用querySelectorAll() 查询DOM 并将NodeList 存储在变量images 中。然后我们循环改变元素的属性。

const btn = document.getElementById('doIt'),
      images = document.querySelectorAll('img');

function addImages(){
  for(let i = 0; i < 6; i++){
     images[i].setAttribute('src', `https://picsum.photos/id/${i}/100/100`);
  }
}

btn.addEventListener('click', addImages);
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<p>
<input type="button" id="doIt" value="add images"/>

【讨论】:

  • 为什么要一遍又一遍地在 DOM 中查询所有图像?
  • 成功了,非常感谢
  • @AbrahamEbijuni 你真的不应该那样做。使用 CSS 选择器,或查询 DOM 一次并将结果存储在变量中并使用该变量。查询 DOM n 次是没有意义的。
  • @Andreas 你能扩展一下吗?如果您也回答了这个问题,也许这将是一个好主意..
  • cmets on OPs question中提到了相关信息。
猜你喜欢
  • 2014-01-07
  • 2023-04-02
  • 2023-01-25
  • 1970-01-01
  • 2022-11-26
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
相关资源
最近更新 更多