logoalt Hacker News

CSS as a Query Language

27 pointsby evnctoday at 5:39 PM12 commentsview on HN

Comments

k1mtoday at 6:33 PM

I find CSS selectors a lot easier to write than XPath. I recently gave a talk on how PHP's new DOM API makes working with HTML and CSS selectors natively very easy (previously you had to convert CSS to XPath).[1]

It's a shame that because CSS is still primarily for browser use and styling, we don't get nice things like the ability to select based on text content like we can with XPath. My understanding is that this was proposed but didn't make it into the spec because it could lead to performance issues in a browser rendering context.

[1] https://speakerdeck.com/keyvan/parsing-html-with-php-8-dot-4...

show 2 replies
spookylukeytoday at 7:19 PM

The project pyastgrep https://pyastgrep.readthedocs.io/en/latest/ can use CSS selectors as a query language for Python syntax (default is XPath).

e.g.:

pyastgrep --css 'Call > func > Name#main'

show 1 reply
duncanfwalkertoday at 7:02 PM

Reminds me of seeing this presented at a conference years ago https://github.com/braposo/graphql-css

It was a joke but I really like the way it pointed out how we copy and reapply patterns in different contexts and that might enable unexpected things.

show 1 reply
efortistoday at 6:24 PM

Not sure I follow the scenario this would solve.

For instance, currently you can conditionally change a parent based on its children. For example, this `pre` could either have 16px or 0px of padding. Zero when its direct child is a `code` element.

  pre {
    padding: 16px;

    &:has(> code) {
      padding: 0;
    }
  }
show 2 replies
securityTalenttoday at 7:48 PM

Nice