实例详解JavaScript获取多个id

 2025-01-15  阅读 600  评论 5  点赞 331

摘要:编写一个在javascript中获取多个id的示例代码。通过在“querySelectorAll”中指定多个“id”。指定不存在的id不会出错。获取多个id使用“querySelectorAll”检索多个“id”。aaa bbb ccc const nodelist = document.querySelectorAll('#one, #two, #three'); for(let

编写一个在javascript中获取多个id的示例代码。

通过在“querySelectorAll”中指定多个“id”。

指定不存在的id不会出错。

实例详解JavaScript获取多个id-第1张-php-LS'Blog-保定PHP程序员老宋个人博客

获取多个id

使用“querySelectorAll”检索多个“id”。

<div id="one">aaa</div>
<div id="two">bbb</div>
<div id="three">ccc</div>

<script>

const nodelist = document.querySelectorAll('#one, #two, #three');

for(let item of nodelist){
  console.log( item.textContent )
}

</script>

执行结果

实例详解JavaScript获取多个id-第2张-php-LS'Blog-保定PHP程序员老宋个人博客

“NodeList”可以作为数组处理,因此也可以使用“forEach”等。

const nodelist = document.querySelectorAll('#one, #two, #three');

nodelist.forEach(v => {
  console.log(v.textContent);
});

还可以在数组中准备“id”,然后检索它。

const ids = ['one', 'two', 'three'];

const nodelist = document.querySelectorAll(
  ids.map(id => `#${id}`).join(', ')
);

for(let item of nodelist){
  console.log( item.textContent )
}

指定一个不存在的id

指定不存在的“id”不会出错。

const nodelist = document.querySelectorAll('#four, #five');

nodelist.forEach(v => {
  console.log(v.textContent); // 不出错,不输出任何内容
});


评论列表:

  •   tg2087002654
     发布于 2025-01-14 10:30:00回复该评论
  • 谢谢分享!
  •   weihang233
     发布于 2025-01-14 16:30:00回复该评论
  • 非常棒谢谢了!
  •   tg2087002654
     发布于 2025-01-14 22:30:00回复该评论
  • 感谢分享!
  •   henbucuo
     发布于 2025-01-15 10:30:00回复该评论
  • 不错,学习了!
显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2471
  • 积分67616
  • 金币91666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0276秒, 内存占用2.04 MB, 访问数据库28次

冀ICP备19034377号