2

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.

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

if there is no native support then?
@ArunPJohny If there is no native support you can shim .map pretty easily yourself, MDN contains a pretty good one developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . It's fine to shim methods that already exist in new JS implementations like .map .filter .reduce and so on :)
I apologize - I'm still a noob. I added two more closing parenthesis "})));" to close the 'var myProps = Array.prototype ......' call but I get an error that that "documentquerySelectorAll is not defined'
@bagofmilk Yeah, that was my bad :) I typed it in the browser, querySelectorAll is a method of document, so it's document.querySelectorAll - note querySelectorAll requires IE8 and up so if you need to support older browsers you need to select the elements differently or use a selector engine like sizzle. Also, no need to apologize, if my answer has a problem in it I want to know - that's one of the reasons I come to SO - to be peer reviewed, and it is also part of how I learn.
Ah cool. Now I get 'undefined is not a function' and it points to the var myProps code. I'm using Chrome BTW.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.