Reputation: 155
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
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