Skip to content

Commit cb3ed67

Browse files
committed
Add attribute existence selectors
1 parent cd411fc commit cb3ed67

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ select(ast, 'paragraph emphasis > text')
3030
- [x] Group selectors: `paragraph, text`
3131
- [x] Universal selector: `*`
3232
- [ ] Attribute selectors: `text[value*="substr"]`
33-
- [ ] Existence: `[value]`
33+
- [x] Existence: `[value]`
3434
- [ ] Equality: `[value="foo"]`
3535
- [ ] Begins with: `[value^="prefix"]`
3636
- [ ] Containment: `[value*="substr"]`

lib/select.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ select.rule = function (selector, ast) {
4646
return result;
4747

4848
function walk (node, parent) {
49-
if (selector.tagName == '*' || node.type == selector.tagName) {
49+
if (matches(selector, node)) {
5050
if (!selector.rule) {
5151
append(result, [node]);
5252
}
@@ -76,6 +76,20 @@ select.rule = function (selector, ast) {
7676
};
7777

7878

79+
// True if node matches head of selector rule.
80+
function matches (rule, node) {
81+
// Match type.
82+
if (rule.tagName && rule.tagName != '*' && node.type != rule.tagName) {
83+
return false;
84+
}
85+
86+
// Match attributes.
87+
return (rule.attrs || []).every(function (attr) {
88+
return attr.name in node;
89+
});
90+
}
91+
92+
7993
function append (array, elements) {
8094
elements.forEach(function (el) {
8195
if (array.indexOf(el) < 0) {

test/test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,10 @@ test('universal selector', function (t) {
9999
}, 0);
100100
}
101101
});
102+
103+
104+
test('attribute selectors', function (t) {
105+
t.deepEqual(select(ast, '[depth]'), select(ast, 'heading'));
106+
t.deepEqual(select(ast, '[start][ordered]'), select(ast, 'list'));
107+
t.end();
108+
});

0 commit comments

Comments
 (0)