diff --git a/Readme.md b/Readme.md index a9f69a57d1..aa8e09eb32 100644 --- a/Readme.md +++ b/Readme.md @@ -822,6 +822,21 @@ $.xml() //=> ``` +You may also render the text content of a Cheerio object using the `text` static method: + +```js +$ = cheerio.load('This is content.') +$.text() +//=> This is content. +``` + +The method may be called on the Cheerio module itself--be sure to pass a collection of nodes! + +```js +$ = cheerio.load('
This is content.
') +cheerio.text($('div')) +//=> This is content. +``` ### Miscellaneous DOM element methods that don't fit anywhere else diff --git a/lib/static.js b/lib/static.js index f206b789d1..16ad5b2d40 100644 --- a/lib/static.js +++ b/lib/static.js @@ -109,7 +109,9 @@ exports.xml = function(dom) { */ exports.text = function(elems) { - if (!elems) return ''; + if (!elems) { + elems = this.root(); + } var ret = '', len = elems.length, diff --git a/test/api/utils.js b/test/api/utils.js index 2ece35b21e..64f5ecb187 100644 --- a/test/api/utils.js +++ b/test/api/utils.js @@ -35,6 +35,28 @@ describe('cheerio', function() { }); + describe('.text', function() { + it('(cheerio object) : should return the text contents of the specified elements', function() { + var $ = cheerio.load('This is content.'); + expect($.text($('a'))).to.equal('This is content.'); + }); + + it('(cheerio object) : should omit comment nodes', function() { + var $ = cheerio.load('This is not a comment.'); + expect($.text($('a'))).to.equal('This is not a comment.'); + }); + + it('(cheerio object) : should include text contents of children recursively', function() { + var $ = cheerio.load('This is
a child with another child and not a comment followed by one last child and some final
text.
'); + expect($.text($('a'))).to.equal('This is a child with another child and not a comment followed by one last child and some final text.'); + }); + + it('() : should return the rendered text content of the root', function() { + var $ = cheerio.load('This is
a child with another child and not a comment followed by one last child and some final
text.
'); + expect($.text()).to.equal('This is a child with another child and not a comment followed by one last child and some final text.'); + }); + }); + describe('.load', function() {