I quickly tried to find the implementation in jQuery’s source, but only found this which doesn’t actually seem to define it completely.
From the jQuery Source
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function() {
return jQuery(this).text( text.call(this) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.getText( this );
},
Anyone know?
Clarification:
I know how to use it. I just want to know how to get the text of an element à la jQuery when jQuery isn’t available.
Text() The Text() constructor returns a new Text object with the optional string given in parameter as its textual content.
Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.
jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.
Projects In JavaScript & JQuery These are DOM related methods. The attributes include, text() and html() too, text() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected.
jQuery.fn.text can be used for 3 different purposes, as the source you pasted clearly shows. The case you're looking for, is the third one - returning the text value of an element.
jQuery uses jQuery.text() method to get the text value of an element, and jQuery.text points to Sizzle.getText()
jQuery.text = Sizzle.getText;
And here's the definition of getText function.
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
Working example: http://jsfiddle.net/cBsDN/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With