Added support for .text() on text nodes. Fixes #5525.

This commit is contained in:
John Resig 2009-11-17 14:52:08 -05:00
parent c08474580c
commit b30af34f28
2 changed files with 15 additions and 10 deletions

View file

@ -31,19 +31,21 @@ if ( !jQuery.support.htmlSerialize ) {
jQuery.fn.extend({ jQuery.fn.extend({
text: function( text ) { text: function( text ) {
if ( typeof text !== "object" && text !== undefined ) if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
var ret = ""; var ret = "";
jQuery.each( text || this, function(){ jQuery.each( this, function() {
jQuery.each( this.childNodes, function(){ // Get the text from text nodes and CDATA nodes
if ( this.nodeType !== 8 ) { if ( this.nodeType === 3 || this.nodeType === 4 ) {
ret += this.nodeType !== 1 ? ret += this.nodeValue;
this.nodeValue :
jQuery.fn.text( [ this ] ); // Traverse everything else, except comment nodes
} } else if ( this.nodeType !== 8 ) {
}); ret += jQuery.fn.text.call( this.childNodes );
}
}); });
return ret; return ret;

View file

@ -4,9 +4,12 @@ var bareObj = function(value) { return value; };
var functionReturningObj = function(value) { return (function() { return value; }); }; var functionReturningObj = function(value) { return (function() { return value; }); };
test("text()", function() { test("text()", function() {
expect(1); expect(2);
var expected = "This link has class=\"blog\": Simon Willison's Weblog"; var expected = "This link has class=\"blog\": Simon Willison's Weblog";
equals( jQuery('#sap').text(), expected, 'Check for merged text of more then one element.' ); equals( jQuery('#sap').text(), expected, 'Check for merged text of more then one element.' );
// Check serialization of text values
equals( jQuery(document.createTextNode("foo")).text(), "foo", "Text node was retreived from .text()." );
}); });
var testWrap = function(val) { var testWrap = function(val) {