Aladdin Mhemed
Aladdin Mhemed

Reputation: 3971

why is "get()" necessary in this example?

I try to understand this example from jquery api in this snippet

        var tags = this.map(function () {
        return this.tagName;
    })
            .get().join(", ");

why get() is necessary? in the api it says that get() Retrieve the DOM elements matched by the jQuery object. In this case, I see that get() is not applied to jq object, but on strings. When I remove get(), I get this error message:

Uncaught TypeError: Object [object Object] has no method 'join'

why join can not work with map?

Upvotes: 0

Views: 95

Answers (2)

apsillers
apsillers

Reputation: 115920

  • Here, this is jQuery object with a list of nodes. (All functions in jQuery.fn have their context (i.e.,this) set to the jQuery object that is making the call to the function.)

  • The call to map returns a jQuery object with a list of strings. (You may be confusing jQuery's map function with the map array function introduced in ECMAScript 5,)

  • The call to get returns a plain JS array of those strings, and join acts on that array.

The call to get is necessary to transform the jQuery object with a list of strings (returned by map) into a plain JS array so it can be glued together with join.

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148524

join is for arrays ( pure js arrays) .

your function returns jquery array which needs to be translated to js plain

.Get() - does that.

http://api.jquery.com/get/

Retrieve the DOM elements matched by the jQuery object.

enter image description here

Upvotes: 0

Related Questions