Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Created January 1, 2019 21:35
Show Gist options
  • Select an option

  • Save lahmatiy/12656e18e4a5272fb8ce8f089455f9d0 to your computer and use it in GitHub Desktop.

Select an option

Save lahmatiy/12656e18e4a5272fb8ce8f089455f9d0 to your computer and use it in GitHub Desktop.

Revisions

  1. lahmatiy created this gist Jan 1, 2019.
    29 changes: 29 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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)}]`);
    });