javascript - 将某个类的所有元素的ID获取到javascript中的数组中

标签 javascript

我读了this question ,并提供了接受的答案:

var ids = $('.cookie').map(function(index) {
    // this callback function will be called once for each matching element
    return this.id; 
});

如何在纯 javascript 中完成上述操作?

最佳答案

我建议如下:

// using Function.prototype.call() to apply 
// Array.prototype.map() to the array-like NodeList returned
// by document.querySelectorAll():
var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
  // the first argument to the anonymous function ('cookie') is
  // the array element of the array over which we're iterating,
  // and is here a DOM node.

  // here, we return the id property of the current node:
  return cookie.id;
});

引用资料:

关于javascript - 将某个类的所有元素的ID获取到javascript中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548942/

相关文章:

javascript - 属性访问器可以在 Javascript 中有原型(prototype)吗

javascript - Dailymotion 停止 iframe 中的视频

javascript - 谷歌地图 onclick 信息窗口在刷新周期后消失

javascript - Bluebird promises - 嵌套与拒绝模式

javascript - Django 表单 : How to edit fields that aren't on the model itself

javascript - Javascript (Node.js) 中的简单命令行提示符

javascript - 将 1 的 JSON 数组转换为对象

javascript - 如何将文字放入圆圈内

javascript - 语法错误 : Invalid regular expression: nothing to repeat

javascript - "Access-Control-Allow-Origin"访问API请求错误