实例详解JavaScript获取多个id
编写一个在javascript中获取多个ID的示例代码。
通过在“querySelectorAll”中指定多个“id”。
指定不存在的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>
执行结果
“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); // 不出错,不输出任何内容 });
文章版权声明:除非注明,否则均为JXLOG原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...