مجاهد
مجاهد

Reputation: 155

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?

Upvotes: 1

Views: 385

Answers (1)

David Thomas
David Thomas

Reputation: 253396

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:

Upvotes: 4

Related Questions