实例详解JavaScript获取多个id

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

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

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

实例详解JavaScript获取多个id

获取多个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

“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); // 不出错,不输出任何内容
});


最后编辑于:2023/03/11作者: 烽烟无限