Skip to content

Commit

Permalink
feat: add :root structural pseudo-class
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Jan 17, 2017
1 parent c7156ce commit c545719
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,32 @@ result === [

```

You can use the `:root` selector to select the current element, e.g.

```js
const document = `
<article class='foo'>A</article>
<article class='bar'>B</article>
`;

const result = x('article {0,}', {
className: x(':root @class'),
textContent: x(':root')
})(document);

result === [
{
className: 'foo',
textContent: 'A'
},
{
className: 'bar',
textContent: 'B'
}
];

```

### Validate the result

Validation is performed using regular expression.
Expand Down
4 changes: 4 additions & 0 deletions src/evaluators/browserEvaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export default (): EvaluatorType => {
};

const querySelectorAll = (node: HTMLElement, selector: string) => {
if (selector.startsWith(':root')) {
return node;
}

return [].slice.apply(node.querySelectorAll(selector));
};

Expand Down
4 changes: 4 additions & 0 deletions src/evaluators/cheerioEvaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export default (): EvaluatorType => {
};

const querySelectorAll = (node: string | Object, selector: string) => {
if (selector.startsWith(':root')) {
return cheerio(node);
}

return cheerio(selector, node).toArray();
};

Expand Down
28 changes: 28 additions & 0 deletions test/expressions/nesting.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,31 @@ test('matches multiple descendant nodes', (t) => {
}
]);
});

test(':root selector accesses attributes and properties of the current element', (t) => {
const x = surgeon();

const document = `
<article class='foo'>A</article>
<article class='bar'>B</article>
`;

const result = x('article {0,}', {
className: x(':root @class'),
tagName: x(':root @.tagName'),
textContent: x(':root')
})(document);

t.deepEqual(result, [
{
className: 'foo',
tagName: 'ARTICLE',
textContent: 'A'
},
{
className: 'bar',
tagName: 'ARTICLE',
textContent: 'B'
}
]);
});

0 comments on commit c545719

Please sign in to comment.