实例详解JavaScript获取多个id

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

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

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

实例详解JavaScript获取多个id  第1张

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

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


本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-queryselectorall.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐