Mini-
Source
Island

A source-code getaway.


.text() [jQuery]

Let's take a look at a straightforward jQuery method, .text().

Eric Saxman | 'Andrelton' - 2015.
Find me on GitHub | LinkedIn.

Example:

  var headerText = $('h1').text();
        

If called with no arguments, as above, .text() simply returns the text of each element. To do this, it uses the .text() method on the local copy of jQuery, which references Sizzle's .getText().

If a new text string is provided, it sets the textContent of each node to that string.

https://code.jquery.com/jquery-2.1.4.js

jQuery.fn.extend({
  text: function( value ) {
    return access( this, function( value ) {
      return value === undefined ?
        jQuery.text( this ) :
        this.empty().each(function() {
          if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            this.textContent = value;
          }
        });
    }, null, value, arguments.length );
  },
...

Sizzle.js is a CSS selector library. It was developed as a part of jQuery, but it is designed to be easily used by other host libraries. It was substantially re-written many years after jQuery was originally released, and it competes well with other selector engines. It is included in-line in the jQuery library.

The jQuery method uses Sizzle's .getText() to get text from DOM nodes. The function flow is fairly straightforward, though it references a native DOM property that few developers may have encountered, nodeType.

If the elem argument is anything other that a single DOM node, getText builds up a string of text in the ret variable. If elem's node type is 'undefined', it is assumed to be an array of elements. getText is called for each element, and its text is added to ret.

If the node is an Element, Document, or DocumentFragment (this is where the nodeType number comes into play), getText returns the value in the .textContent property. If it is a literal text node (or the deprecated 'CDATASection' node...), the nodeValue is returned.

jQuery.text = Sizzle.getText;
...

getText = Sizzle.getText = function( elem ) {
  var node,
    ret = "",
    i = 0,
    nodeType = elem.nodeType;

  if ( !nodeType ) {
    // If no nodeType, this is expected to be an array
    while ( (node = elem[i++]) ) {
      ret += getText( node );
    }

  } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {

    if ( typeof elem.textContent === "string" ) {
      return elem.textContent;
    } else {
      // Traverse its children
      for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
        ret += getText( elem );
      }
    }

  } else if ( nodeType === 3 || nodeType === 4 ) {
    return elem.nodeValue;
  }

  return ret;
};