Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Created January 1, 2019 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lahmatiy/c0ea23a2f0ea091bd042d1f353fbf6f7 to your computer and use it in GitHub Desktop.
Save lahmatiy/c0ea23a2f0ea091bd042d1f353fbf6f7 to your computer and use it in GitHub Desktop.
const cssTree = require("css-tree@1.0.0-alpha.29");
function getSelectorParent(selector) {
const selectorAst = cssTree.parse(selector, { context: 'selector' });
// solution #1
// selectorAst.children.prevUntil(selectorAst.children.tail, (node, item, list) => {
// list.remove(item);
// return node.type === 'Combinator' || node.type === 'WhiteSpace';
// });
// solution #2
let item;
while (item = selectorAst.children.pop()) {
const node = item.data;
if (node.type === 'Combinator' || node.type === 'WhiteSpace') {
break;
}
}
return cssTree.generate(selectorAst);
}
[
'.foo .bar',
'.foo',
'div>p'
].forEach(selector => {
console.log(`[${selector}] -parent-> [${getSelectorParent(selector)}]`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment