Skip to content

Commit

Permalink
Implement $.fn.get
Browse files Browse the repository at this point in the history
  • Loading branch information
jugglinmike committed Mar 13, 2014
1 parent e74025e commit 0ff539e
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
16 changes: 16 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 9 additions & 0 deletions lib/api/traversing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
};
Expand Down
2 changes: 1 addition & 1 deletion lib/cheerio.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Cheerio.prototype._make = function(dom) {
*/

Cheerio.prototype.toArray = function() {
return [].slice.call(this, 0);
return this.get();
};

/**
Expand Down
29 changes: 29 additions & 0 deletions test/api.traversing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 0ff539e

Please sign in to comment.