I’ve recently come across a code sample I had to use, and I was able to use it, but I didn’t quite understand exactly what was going on.
Here’s part of the code:
.sortElements(function(a, b){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
I know that this function is deciding which element should be sorted first out of a and b, and I know that inverse is deciding the sort order, but I don’t know what $.text([a]) is doing. Is it parsing a as text kind of like parseInt(a) and Date.parse(a)?
Google could not help me. I’ve also looked into the jQuery site and all I’ve found is
$(selector).text(), $(selector).text(newText) function.
Here’s the Fiddle I’m basing my code from http://jsfiddle.net/gFzCk/
Inspecting the jQuery source will reveal that the
$(selector).text()that you’re familiar with, uses$.textinternally:It is an undocumented function (which means further jQuery revisions may drop it at will, without notifying you). You’ll find its definition as such:
Sizzle.getText, in turn, is documented as “Utility function for retrieving the text value of an array of DOM nodes”. Seeing asSizzle.getTextis a documented feature, I would recommend using that rather than the jQuery shorthand, as I don’t expect jQuery to drop Sizzle any time soon.This function, then, is the piece of code that yields the text content of a DOM node. Your sorting method is sorting DOM nodes by the alphabetical order of their text content. I don’t know why the author has decided to get the text of an array containing only one element (
[a]), rather than passing the element immediately (a), which would work equally well.