Git Product home page Git Product logo

hast-util-select's Introduction

hast-util-select

Build Coverage Downloads Size Sponsors Backers Chat

hast utility with equivalents for matches, querySelector, and querySelectorAll.

Contents

What is this?

This package lets you find nodes in a tree, similar to how matches, querySelector, and querySelectorAll work with the DOM.

One notable difference between DOM and hast is that DOM nodes have references to their parents, meaning that document.body.matches(':last-child') can be evaluated to check whether the body is the last child of its parent. This information is not stored in hast, so selectors like that don’t work.

When should I use this?

This is a small utility that is quite useful, but is rather slow if you use it a lot. For each call, it has to walk the entire tree. In some cases, walking the tree once with unist-util-visit is smarter, such as when you want to change certain nodes. On the other hand, this is quite powerful and fast enough for many other cases.

This utility is similar to unist-util-select, which can find and match any unist node.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install hast-util-select

In Deno with esm.sh:

import {matches, select, selectAll} from "https://esm.sh/hast-util-select@6"

In browsers with esm.sh:

<script type="module">
  import {matches, select, selectAll} from "https://esm.sh/hast-util-select@6?bundle"
</script>

Use

import {h} from 'hastscript'
import {matches, select, selectAll} from 'hast-util-select'

const tree = h('section', [
  h('p', 'Alpha'),
  h('p', 'Bravo'),
  h('h1', 'Charlie'),
  h('p', 'Delta'),
  h('p', 'Echo'),
  h('p', 'Foxtrot'),
  h('p', 'Golf')
])

console.log(matches('section', tree)) // `true`

console.log(select('h1 ~ :nth-child(even)', tree))
// The paragraph with `Delta`

console.log(selectAll('h1 ~ :nth-child(even)', tree))
// The paragraphs with `Delta` and `Foxtrot`

API

This package exports the identifiers matches, select, and selectAll. There is no default export.

matches(selector, node[, space])

Check that the given node matches selector.

This only checks the element itself, not the surrounding tree. Thus, nesting in selectors is not supported (p b, p > b), neither are selectors like :first-child, etc. This only checks that the given element matches the selector.

Parameters
  • selector (string) — CSS selector, such as (h1, a, b)
  • node (Node, optional) — node that might match selector, should be an element
  • space (Space, default: 'html') — name of namespace
Returns

Whether node matches selector (boolean).

Example
import {h} from 'hastscript'
import {matches} from 'hast-util-select'

matches('b, i', h('b')) // => true
matches(':any-link', h('a')) // => false
matches(':any-link', h('a', {href: '#'})) // => true
matches('.classy', h('a', {className: ['classy']})) // => true
matches('#id', h('a', {id: 'id'})) // => true
matches('[lang|=en]', h('a', {lang: 'en'})) // => true
matches('[lang|=en]', h('a', {lang: 'en-GB'})) // => true

select(selector, tree[, space])

Select the first element that matches selector in the given tree. Searches the tree in preorder.

Parameters
  • selector (string) — CSS selector, such as (h1, a, b)
  • tree (Node, optional) — tree to search
  • space (Space, default: 'html') — name of namespace
Returns

First element in tree that matches selector or undefined if nothing is found. This could be tree itself.

Example
import {h} from 'hastscript'
import {select} from 'hast-util-select'

console.log(
  select(
    'h1 ~ :nth-child(even)',
    h('section', [
      h('p', 'Alpha'),
      h('p', 'Bravo'),
      h('h1', 'Charlie'),
      h('p', 'Delta'),
      h('p', 'Echo')
    ])
  )
)

Yields:

{ type: 'element',
  tagName: 'p',
  properties: {},
  children: [ { type: 'text', value: 'Delta' } ] }

selectAll(selector, tree[, space])

Select all elements that match selector in the given tree. Searches the tree in preorder.

Parameters
  • selector (string) — CSS selector, such as (h1, a, b)
  • tree (Node, optional) — tree to search
  • space (Space, default: 'html') — name of namespace
Returns

Elements in tree that match selector. This could include tree itself.

Example
import {h} from 'hastscript'
import {selectAll} from 'hast-util-select'

console.log(
  selectAll(
    'h1 ~ :nth-child(even)',
    h('section', [
      h('p', 'Alpha'),
      h('p', 'Bravo'),
      h('h1', 'Charlie'),
      h('p', 'Delta'),
      h('p', 'Echo'),
      h('p', 'Foxtrot'),
      h('p', 'Golf')
    ])
  )
)

Yields:

[ { type: 'element',
    tagName: 'p',
    properties: {},
    children: [ { type: 'text', value: 'Delta' } ] },
  { type: 'element',
    tagName: 'p',
    properties: {},
    children: [ { type: 'text', value: 'Foxtrot' } ] } ]

Space

Namespace (TypeScript type).

Type
type Space = 'html' | 'svg'

Support

  • * (universal selector)
  • , (multiple selector)
  • p (type selector)
  • .class (class selector)
  • #id (id selector)
  • article p (combinator: descendant selector)
  • article > p (combinator: child selector)
  • h1 + p (combinator: next-sibling selector)
  • h1 ~ p (combinator: subsequent sibling selector)
  • [attr] (attribute existence)
  • [attr… i] (attribute case-insensitive)
  • [attr… s] (attribute case-sensitive) (useless, default)
  • [attr=value] (attribute equality)
  • [attr~=value] (attribute contains in space-separated list)
  • [attr|=value] (attribute equality or prefix)
  • [attr^=value] (attribute begins with)
  • [attr$=value] (attribute ends with)
  • [attr*=value] (attribute contains)
  • :dir() (functional pseudo-class)
  • :has() (functional pseudo-class; also supports a:has(> b))
  • :is() (functional pseudo-class)
  • :lang() (functional pseudo-class)
  • :not() (functional pseudo-class)
  • :any-link (pseudo-class)
  • :blank (pseudo-class)
  • :checked (pseudo-class)
  • :disabled (pseudo-class)
  • :empty (pseudo-class)
  • :enabled (pseudo-class)
  • :optional (pseudo-class)
  • :read-only (pseudo-class)
  • :read-write (pseudo-class)
  • :required (pseudo-class)
  • :root (pseudo-class)
  • :scope (pseudo-class):
  • * :first-child (pseudo-class)
  • * :first-of-type (pseudo-class)
  • * :last-child (pseudo-class)
  • * :last-of-type (pseudo-class)
  • * :only-child (pseudo-class)
  • * :only-of-type (pseudo-class)
  • * :nth-child() (functional pseudo-class)
  • * :nth-last-child() (functional pseudo-class)
  • * :nth-last-of-type() (functional pseudo-class)
  • * :nth-of-type() (functional pseudo-class)

Unsupported

  • || (column combinator)
  • ns|E (namespace type selector)
  • *|E (any namespace type selector)
  • |E (no namespace type selector)
  • [ns|attr] (namespace attribute)
  • [*|attr] (any namespace attribute)
  • [|attr] (no namespace attribute)
  • :nth-child(n of S) (functional pseudo-class, note: scoping to parents is not supported)
  • :nth-last-child(n of S) (functional pseudo-class, note: scoping to parents is not supported)
  • :active (pseudo-class)
  • :autofill (pseudo-class)
  • :buffering (pseudo-class)
  • § :closed (pseudo-class)
  • :current (pseudo-class)
  • :current() (functional pseudo-class)
  • :default (pseudo-class)
  • :defined (pseudo-class)
  • :focus (pseudo-class)
  • :focus-visible (pseudo-class)
  • :focus-within (pseudo-class)
  • :fullscreen (pseudo-class)
  • :future (pseudo-class)
  • § :host() (functional pseudo-class)
  • § :host-context() (functional pseudo-class)
  • :hover (pseudo-class)
  • :in-range (pseudo-class)
  • :indeterminate (pseudo-class)
  • :invalid (pseudo-class)
  • :link (pseudo-class)
  • :local-link (pseudo-class)
  • :modal (pseudo-class)
  • :muted (pseudo-class)
  • :nth-col() (functional pseudo-class)
  • :nth-last-col() (functional pseudo-class)
  • § :open (pseudo-class)
  • :out-of-range (pseudo-class)
  • :past (pseudo-class)
  • :paused (pseudo-class)
  • :placeholder-shown (pseudo-class)
  • :playing (pseudo-class)
  • :seeking (pseudo-class)
  • :stalled (pseudo-class)
  • :target (pseudo-class)
  • :target-within (pseudo-class)
  • :user-invalid (pseudo-class)
  • :valid (pseudo-class)
  • :visited (pseudo-class)
  • :volume-locked (pseudo-class)
  • § :where() (functional pseudo-class)
  • ::before (pseudo-elements: none are supported)
Notes
  • * — not supported in matches
  • † — needs a user, browser, interactivity, scripting, or whole CSS to make sense
  • ‡ — not very interested in writing / including the code for this
  • § — too new, the spec is still changing
  • ‖ — pr wanted!
  • :any() and :matches() are renamed to :is() in CSS.

Types

This package is fully typed with TypeScript. It exports the additional type Space.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, hast-util-select@^6, compatible with Node.js 16.

Security

This package does not change the syntax tree so there are no openings for cross-site scripting (XSS) attacks.

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

hast-util-select's People

Contributors

wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

jenseng

hast-util-select's Issues

Typescript support

Subject of the feature

Are you open to adding an index.d.ts file?

Problem

I made a d.ts for this - that I have been using. Happy to PR it back to the project.

Expected behavior

VS Code Intelisense to show expected types.

Alternatives

I could submit directly to DefinitelyTyped - but I think their bots may ping you anyway. (Not sure, never PRd to DT before)

How to work with custom tags?

Greetings!

I use this tool, with custom html like tree.
When i use a custom tag where "tagName": "title", i cannot get children tags, because they are stringified.

I know this tool is for standard html, but i like to use for my custom data structures.
So i cannot use "title" named tag, and i dont know which tag has similar problems.

Maybe this is the required behaviour for standard usage, and not fixable, but i just wanted to write here, if anybody would use custom tags, this could happen.

Can't use parent-sensitive pseudoselectors with :not

Initial checklist

Affected packages and versions

[email protected]

Link to runnable example

https://runkit.com/quarterto/6397058cb17f2300086ba513

Steps to reproduce

import {h} from 'hastscript'
import {selectAll} from 'hast-util-select'

selectAll('img:not(:first-child)`, h('body', [
    h('img', { src: 'https://example.com/one' }),
    h('p', ['text']),
    h('img', { src: 'https://example.com/two' }),
]))

Expected behavior

it selects the second img

Actual behavior

Error: Cannot use `:first-child` without parent

this is because :not is implemented using matches, which doesn't support parent-sensitive pseudos

Affected runtime and version

node@14, node@16

Affected package manager and version

No response

Affected OS and version

No response

Build and bundle tools

No response

Non-elements between adjacent and general sibling combinators should be skipped

This does not work:

    st.deepEqual(
      select(
        'h1 + p',
        u('root', [
          u('text', '\n'),
          h('p', 'Alpha'),
          u('text', '\n'),
          h('h1', 'Bravo'),
          u('text', '\n'),
          h('p', 'Charlie'),
          u('text', '\n'),
          h('p', 'Delta'),
          u('text', '\n'),
          h('div', [h('p', 'Echo')])
        ])
      ),
      h('p', 'Charlie'),
      'should return adjacent sibling (whitespace)'
    )

It does work if there is no inter-element whitespace.

Affects +, but probably also ~ and >

`:not()` selector no longer supported with multiple matches

Initial checklist

Affected packages and versions

5.0.4

Link to runnable example

https://codesandbox.io/p/sandbox/peaceful-rumple-nnr5qz?file=%2Findex.js&selection=%5B%7B%22endColumn%22%3A7%2C%22endLineNumber%22%3A24%2C%22startColumn%22%3A7%2C%22startLineNumber%22%3A24%7D%5D

Steps to reproduce

import { selectAll } from "hast-util-select";
import { s } from "hastscript";
const tree = s("svg", [
  s("circle", { fill: "#333" }),
  s("circle", { fill: "none" }),
  s("circle", { fill: "none" }),
  s("circle"),
  s("rect", { fill: "#666666" }),
  s("rect", { fill: "none" }),
  s("rect", { fill: "none" }),
  s("rect", { fill: "none" }),
  s("rect"),
]);

const result = selectAll("circle:not([fill]), rect:not([fill])", tree);

// Should select just 1 circle, 1 rect.
console.log(result);

// But we get:

// [
//   { type: 'element', tagName: 'circle', properties: {}, children: [] },
//   {
//     type: 'element',
//     tagName: 'rect',
//     properties: { fill: '#666666' },
//     children: []
//   },
//   {
//     type: 'element',
//     tagName: 'rect',
//     properties: { fill: 'none' },
//     children: []
//   },
//   {
//     type: 'element',
//     tagName: 'rect',
//     properties: { fill: 'none' },
//     children: []
//   },
//   {
//     type: 'element',
//     tagName: 'rect',
//     properties: { fill: 'none' },
//     children: []
//   },
//   { type: 'element', tagName: 'rect', properties: {}, children: [] }
// ]

Expected behavior

It should just 1 circle and 1 rect.

Actual behavior

It selects a bunch of elements that don't match the query.

Affected runtime and version

[email protected], [email protected]

Affected package manager and version

No response

Affected OS and version

No response

Build and bundle tools

No response

data-* attribute selection doesn't work

Initial checklist

Affected packages and versions

hast-util-select@6

Link to runnable example

https://jsbin.com/lihidasupa/1/edit?html,console

Steps to reproduce

  1. create an element with a data-* attribute
  2. try to find it with an attribute selector

Expected behavior

Element should be found

Actual behavior

Element isn't found

Affected runtime and version

chromium@Version 121.0.6167.85 (Official Build) Arch Linux (64-bit)

Affected package manager and version

No response

Affected OS and version

No response

Build and bundle tools

No response

How to use rehype?

Hello - I try use it for search all elements

var body = '<!DOCTYPE html><html lang="en"><p></p></html>';
var h = require('hastscript');
var selectAll = require('hast-util-select').selectAll;
console.log(
    selectAll(
        'p',
        h('html', body)
    )
);
console.log(
    selectAll(
        'p',
        body
    )
);
console.log(
    selectAll(
        'p',
        h(body)
    )
);

but I get everytime only

[]
[]
[]

Q can you help?

Bruno

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.