Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript methods that can not be called from jquery objects?

I was reading Learning jQuery 1.3 (Jonathan Chaffer and Karl Swedberg) and while sorting table, they used .get() before calling .sort(), and said

we need to transform jQuery objects into array of DOM nodes. Even though jQuery objects act like arrays in many respects , they don't have any of the native array methods available, such as .sort().

Code:

$("#sort").click(function() {
        var posts = $("#posts_div .post");
        posts.sort(function(a, b) {
           return ($(a).text()) > ($(b).text());
        });       
        $.each(posts, function(index, post) { $("#posts_div").append(post); });
});​

So I tried to do it without using .get(), but surprise it worked even without .get() with latest jQuery, but didn't work with 1.3

So made some fiddles to make it clear

**Not working without .get() jquery 1.2.6 **

Working with .get() jquery 1.2.6

Working without .get() jquery 1.7.2

Working with .get() jquery 1.7.2

So obviously earlier jQuery objects didn't used to have .sort() function same as Javascript arrays? But now they have..

So my question is what are the functions the jQuery objects not support yet, so we can keep in mind to convert to Javascript arrays, before use??

like image 319
Rajat Singhal Avatar asked Jun 22 '12 14:06

Rajat Singhal


People also ask

Which is not jQuery method?

jQuery not() MethodThe not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed.

Which of them have no methods in JavaScript?

The special primitives null and undefined are exceptions. They have no corresponding “wrapper objects” and provide no methods.


2 Answers

jQuery objects currently support 3 array methods:

var methods = 'pop push reverse shift sort splice unshift concat join slice toString indexOf lastIndexOf filter forEach every map some reduce reduceRight'.split(' ')
var implemented = $.grep(methods, function(m) {
    return $.prototype[m] == Array.prototype[m];
});
console.log(implemented); // => ["push", "sort", "splice"]

They also have slice, but it's not the same slice as arrays have:

$.prototype.slice === Array.prototype.slice // => false
like image 83
Alexey Lebedev Avatar answered Sep 30 '22 14:09

Alexey Lebedev


jQuery does have a .sort method, it just isn't officially documented because it does not follow the usual format of jQuery methods.

The only methods that are supported are the ones listed in the api.

.sort is implemented as:

$.fn.sort = [].sort;

You can add your own additional array methods as needed in the same way.

$.fn.reverse = [].reverse;

If .sort isn't implemented in your version of jQuery, implement it yourself.

like image 35
Kevin B Avatar answered Sep 30 '22 12:09

Kevin B