Skip to content

Commit

Permalink
fix(find): Make it possible to find siblings (#1583)
Browse files Browse the repository at this point in the history
Fixes #1244
Fixes #1095
  • Loading branch information
fb55 committed Dec 22, 2020
1 parent 88ae636 commit 1062a6c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
19 changes: 14 additions & 5 deletions lib/api/traversing.js
Expand Up @@ -9,6 +9,7 @@ var utils = require('../utils');
var domEach = utils.domEach;
var uniqueSort = require('htmlparser2').DomUtils.uniqueSort;
var isTag = utils.isTag;
var reSiblingSelector = /^\s*[~+]/;

/**
* Get the descendants of each element in the current set of matched elements,
Expand All @@ -26,9 +27,6 @@ var isTag = utils.isTag;
* @see {@link http://api.jquery.com/find/}
*/
exports.find = function (selectorOrHaystack) {
var elems = this.toArray().reduce(function (newElems, elem) {
return newElems.concat(elem.children.filter(isTag));
}, []);
var contains = this.constructor.contains;
var haystack;

Expand All @@ -52,9 +50,20 @@ exports.find = function (selectorOrHaystack) {
);
}

var options = { __proto__: this.options, context: this.toArray() };
if (!selectorOrHaystack) {
return this._make([]);
}

var context = this.toArray();
var elems = reSiblingSelector.test(selectorOrHaystack)
? context
: context.reduce(function (newElems, elem) {
return newElems.concat(elem.children.filter(isTag));
}, []);

var options = Object.assign({ context: context }, this.options);

return this._make(select.select(selectorOrHaystack || '', elems, options));
return this._make(select.select(selectorOrHaystack, elems, options));
};

/**
Expand Down
9 changes: 9 additions & 0 deletions test/api/traversing.js
Expand Up @@ -61,6 +61,15 @@ describe('$(...)', function () {
expect(q('foo').find('> bar')).to.have.length(1);
});

it('should find siblings', function () {
var q = cheerio.load('<p class=a><p class=b></p>');
expect(q('.a').find('+.b')).to.have.length(1);
expect(q('.a').find('~.b')).to.have.length(1);
// Should not find itself
expect(q('.a').find('+.a')).to.have.length(0);
expect(q('.a').find('~.a')).to.have.length(0);
});

it('should query case-sensitively when in xml mode', function () {
var q = cheerio.load('<caseSenSitive allTheWay>', { xml: true });
expect(q('caseSenSitive')).to.have.length(1);
Expand Down

0 comments on commit 1062a6c

Please sign in to comment.