使用jQuery、JavaScript获取含指定类元素的所有ID并保存为数组是否可行?
获取指定类元素的ID并保存为数组
当然没问题!不管你用jQuery还是原生JavaScript,都能轻松实现这个需求,我给你分别写两种方案,你可以根据项目环境来选:
使用jQuery实现
思路很简单:先选中所有带有目标类的元素,接着用map()方法遍历每个元素提取它的id属性,最后用get()把jQuery对象转换成普通数组即可。
示例代码:
// 替换成你要查找的目标类名 const targetClassName = 'your-target-class'; const idsArray = $(`.${targetClassName}`).map(function() { // 返回当前元素的id return this.id; }).get(); // 打印结果看看 console.log(idsArray);
如果担心有些匹配元素可能没有设置id,可以加个过滤步骤,去掉空值:
const idsArray = $(`.${targetClassName}`).map(function() { return this.id || null; }).get().filter(id => id !== null);
使用原生JavaScript实现
原生JS的话,我们可以用document.querySelectorAll()选中目标元素,然后把它转换成数组后用map()提取id,有两种转换数组的方式:
方法一:使用Array.from()
const targetClassName = 'your-target-class'; const elements = document.querySelectorAll(`.${targetClassName}`); const idsArray = Array.from(elements).map(el => el.id); console.log(idsArray);
方法二:使用展开运算符...
const targetClassName = 'your-target-class'; const idsArray = [...document.querySelectorAll(`.${targetClassName}`)].map(el => el.id); console.log(idsArray);
同样,如果要过滤空id,只需要在后面加个filter():
const idsArray = [...document.querySelectorAll(`.${targetClassName}`)] .map(el => el.id) .filter(id => id); // 空字符串会被自动过滤掉
内容的提问来源于stack exchange,提问作者Mähmøđ Łővãķ Dwǻwệen
相关产品推荐
相关产品推荐

