Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.text(["someText"]) - What does it mean?

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/

like image 402
Owen Avatar asked Feb 05 '13 09:02

Owen


3 Answers

jQuery.text does the heavy lifting for the implementation for the .text() method -- it seems to be an undocumented function with the core functionality for .text(), but missing some jQuery polish.

It's "imported" from Sizzle, where it appears as Sizzle.getText.

like image 179
Jon Avatar answered Nov 17 '22 13:11

Jon


Inspecting the jQuery source will reveal that the $(selector).text() that you're familiar with, uses $.text internally:

jQuery.fn.extend({
    text: function( value ) {
        return jQuery.access( this, function( value ) {
            return value === undefined ?
                jQuery.text( this ) :
                this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
        }, null, value, arguments.length );
    },

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:

jQuery.text = Sizzle.getText;

Sizzle.getText, in turn, is documented as "Utility function for retrieving the text value of an array of DOM nodes". Seeing as Sizzle.getText is 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.

like image 44
David Hedlund Avatar answered Nov 17 '22 12:11

David Hedlund


After looking at your jsfiddle it appears it's a function for getting the text from an element, simular to .text()

console.log(a) logged <td>28/02/2013</td>

While

console.log($.text[a]) logged 28/02/2013

like image 2
Kolby Avatar answered Nov 17 '22 11:11

Kolby