diff --git a/Readme.md b/Readme.md index c3084dbfc7..36f96b5712 100644 --- a/Readme.md +++ b/Readme.md @@ -442,6 +442,22 @@ $('li').eq(-1).text() //=> Pear ``` +#### .get( [i] ) + +Retrieve the DOM elements matched by the Cheerio object. If an index is specified, retrieve one of the elements matched by the Cheerio object: + +```js +$('li').get(0).name +//=> li +``` + +If no index is specified, retrieve all elements matched by the Cheerio object: + +```js +$('li').get().length +//=> 3 +``` + #### .end() End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. diff --git a/lib/api/traversing.js b/lib/api/traversing.js index 39a421c6c6..0fc0298185 100644 --- a/lib/api/traversing.js +++ b/lib/api/traversing.js @@ -287,6 +287,15 @@ var eq = exports.eq = function(i) { return this[i] ? this._make(this[i]) : this._make([]); }; +// Retrieve the DOM elements matched by the jQuery object. +var get = exports.get = function(i) { + if (i == null) { + return Array.prototype.slice.call(this); + } else { + return this[i < 0 ? (this.length + i) : i]; + } +}; + var slice = exports.slice = function() { return this._make([].slice.apply(this, arguments)); }; diff --git a/lib/cheerio.js b/lib/cheerio.js index 7577f2e9e4..bc1f7f94ee 100644 --- a/lib/cheerio.js +++ b/lib/cheerio.js @@ -142,7 +142,7 @@ Cheerio.prototype._make = function(dom) { */ Cheerio.prototype.toArray = function() { - return [].slice.call(this, 0); + return this.get(); }; /** diff --git a/test/api.traversing.js b/test/api.traversing.js index 09543ef1e6..9cbb0ca723 100644 --- a/test/api.traversing.js +++ b/test/api.traversing.js @@ -704,6 +704,35 @@ describe('$(...)', function() { }); + describe('.get', function() { + + it('(i) : should return the element at the specified index', function() { + var children = $(fruits).children(); + expect(children.get(0)).to.be(children[0]); + expect(children.get(1)).to.be(children[1]); + expect(children.get(2)).to.be(children[2]); + }); + + it('(-1) : should return the element indexed from the end of the collection', function() { + var children = $(fruits).children(); + expect(children.get(-1)).to.be(children[2]); + expect(children.get(-2)).to.be(children[1]); + expect(children.get(-3)).to.be(children[0]); + }); + + it('() : should return an array containing all of the collection', function() { + var children = $(fruits).children(); + var all = children.get(); + expect(Array.isArray(all)).to.be.ok(); + expect(all).to.eql([ + children[0], + children[1], + children[2] + ]); + }); + + }); + describe('.slice', function() { function getText(el) {