bagofmilk
bagofmilk

Reputation: 1550

jQuery .map() to pure javascript

Is there a way to convert the following jQuery method to pure javascript?

var myProps = 
$(".interp").map(function () {
return this.id; 
}).get();

I do not know how many objects will be available each time. There may be 3, 15, 20, etc.. objects in the map.

Upvotes: 2

Views: 1643

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

Pure JavaScript contains a .map method too, it's on Array so you'd need to use it on the NodeList returned from querySelectorAll generically using .call:

var myProps =  Array.prototype.map.call(document.querySelectorAll(".interp"),function (el) {
    return el.id; 
});

Alternatively, you can convert the NodeList to an array and use more compact syntax.

function query(selector){
    return Array.prototype.slice.call(document.querySelectorAll(selector),0);
}

Which would let you do:

query(".interp").map(function(el){
    return el.id;
}

Upvotes: 6

Related Questions