hast-util-from-selector

hast utility to parse CSS selectors to hast nodes

Usage no npm install needed!

<script type="module">
  import hastUtilFromSelector from 'https://cdn.skypack.dev/hast-util-from-selector';
</script>

README

hast-util-from-selector

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to create nodes from an advanced CSS selector.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install hast-util-from-selector

Use

import {fromSelector} from 'hast-util-from-selector'

console.log(fromSelector('p svg[viewbox=0 0 10 10] circle[cx=10][cy=10][r=10]'))

Yields:

{
  type: 'element',
  tagName: 'p',
  properties: {},
  children: [
    {
      type: 'element',
      tagName: 'svg',
      properties: {viewBox: '0 0 10 10'},
      children: [
        {
          type: 'element',
          tagName: 'circle',
          properties: {cx: '10', cy: '10', r: '10'},
          children: []
        }
      ]
    }
  ]
}

API

This package exports the following identifiers: fromSelector. There is no default export.

fromSelector([selector][, options])

Create one or more element nodes from a CSS selector.

Parameters
  • selector (string, optional) — CSS selector
  • space (string, optional) — Treated as options.space
  • options.space (enum, 'svg' or 'html', default: 'html') — Which space first element in the selector is in. When an svg is created in HTML, the space is switched automatically to SVG
Returns

Element.

Support

  • * (universal selector, creates a div in HTML, g in SVG)
  • p (type selector)
  • .class (class selector)
  • #id (id selector)
  • [attr] (attribute existence, creates a boolean)
  • [attr=value] (attribute equality)
  • article p (descendant combinator)
  • article > p (child combinator)
  • section h1 + p (next-sibling combinator, not at root)
  • section h1 ~ p (subsequent-sibling combinator, not at root)

Security

Use of from-selector can open you up to a cross-site scripting (XSS) attack as values are injected into the syntax tree.

Either do not use user input in from-selector or use hast-util-santize.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer