简体   繁体   中英

Getting ID of all elements of a certain class into an array in javascript

I read this question , and the accepted answer provided:

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

How can the above be done in pure javascript?

I'd suggest the following:

// 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;
});

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM