Created
January 1, 2019 21:41
-
-
Save lahmatiy/1f053ed83eb8acabc789172dc08d8d59 to your computer and use it in GitHub Desktop.
Get a selector parent selector with csstree (an issue https://twitter.com/peterbe/status/1079854825880326144)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cssTree = require("[email protected]"); | |
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