Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

a CSS selector compiler & engine

License

NotificationsYou must be signed in to change notification settings

fb55/css-select

Repository files navigation

A CSS selector compiler and engine

What?

As acompiler, css-select turns CSS selectors into functions that tests ifelements match them.

As anengine, css-select looks through a DOM tree, searching for elements.Elements are tested "from the top", similar to how browsers execute CSSselectors.

In its default configuration, css-select queries the DOM structure of thedomhandler module (also known ashtmlparser2 DOM). To query alternative DOM structures, seeOptionsbelow.

Features:

  • 🔬 Full implementation of CSS3 selectors, as well as most CSS4 selectors
  • 🧪 Partial implementation of jQuery/Sizzle extensions (seecheerio-select for theremaining selectors)
  • 🧑‍🔬 High test coverage, including the full test suites fromSizzle,Qwery andNWMatcher and .
  • 🥼 Reliably great performance

Why?

Most CSS engines written in JavaScript execute selectors left-to-right. Thatmeans they execute every component of the selector in order, from left to right.As an example: For the selectora b, these engines will first query foraelements, then search these forb elements. (That's the approach of eg.Sizzle,Qwery andNWMatcher.)

While this works, it has some downsides: Children ofas will be checkedmultiple times; first, to check if they are alsoas, then, for every superiora once, if they arebs. UsingBig O notation, that would beO(n^(k+1)), wherek is the number of descendant selectors (that's the spacein the example above).

The far more efficient approach is to first look forb elements, then check ifthey have superiora elements: Using big O notation again, that would beO(n). That's called right-to-left execution.

And that's what css-select does – and why it's quite performant.

How does it work?

By building a stack of functions.

Wait, what?

Okay, so let's suppose we want to compile the selectora b, for right-to-leftexecution. We start byparsing the selector. This turns the selector into anarray of the building blocks. That's what thecss-what module is for, if you want tohave a look.

Anyway, after parsing, we end up with an array like this one:

[{type:"tag",name:"a"},{type:"descendant"},{type:"tag",name:"b"},];

(Actually, this array is wrapped in another array, but that's another story,involving commas in selectors.)

Now that we know the meaning of every part of the selector, we can compile it.That is where things become interesting.

The basic idea is to turn every part of the selector into a function, whichtakes an element as its only argument. The function checks whether a passedelement matches its part of the selector: If it does, the element is passed tothe next function representing the next part of the selector. That function doesthe same. If an element is accepted by all parts of the selector, itmatchesthe selector and double rainbow ALL THE WAY.

As said before, we want to do right-to-left execution with all the big Oimprovements. That means elements are passed from the rightmost part of theselector (b in our example) to the leftmost (which would bec of coursea).

For traversals, such as thedescendant operating the space betweena andb, we walk up the DOM tree, starting from the element passed as argument.

//TODO: More in-depth description. Implementation details. Build a spaceship.

API

constCSSselect=require("css-select");

Note: css-select throws errors when invalid selectors are passed to it. Thisis done to aid with writing css selectors, but can be unexpected when processingarbitrary strings.

CSSselect.selectAll(query, elems, options)

Querieselems, returns an array containing all matches.

  • query can be either a CSS selector or a function.
  • elems can be either an array of elements, or a single element. If it is anelement, its children will be queried.
  • options is described below.

Aliases:default export,CSSselect.iterate(query, elems).

CSSselect.compile(query, options)

Compiles the query, returns a function.

CSSselect.is(elem, query, options)

Tests whether or not an element is matched byquery.query can be either aCSS selector or a function.

CSSselect.selectOne(query, elems, options)

Arguments are the same as forCSSselect.selectAll(query, elems). Only returnsthe first match, ornull if there was no match.

Options

All options are optional.

  • xmlMode: When enabled, tag names will be case-sensitive. Default:false.
  • rootFunc: The last function in the stack, will be called with the lastelement that's looked at.
  • adapter: The adapter to use when interacting with the backing DOM structure.By default it uses thedomutils module.
  • context: The context of the current query. Used to limit the scope ofsearches. Can be matched directly using the:scope pseudo-class.
  • relativeSelector: By default, selectors are relative to thecontext, whichmeans that no parent elements of the context will be matched. (Eg.a b cwith contextb will never give any results.) IfrelativeSelector is set tofalse, selectors won't beabsolutized and selectors cantest for parent elements outside of thecontext.
  • cacheResults: Allow css-select to cache results for some selectors,sometimes greatly improving querying performance. Disable this if yourdocument can change in between queries with the same compiled selector.Default:true.
  • pseudos: A map of pseudo-class names to functions or strings.

Custom Adapters

A custom adapter must match the interface describedhere.

You may want to have a look atdomutils tosee the default implementation, or atcss-select-browser-adapterfor an implementation backed by the DOM.

Supported selectors

As defined by CSS 4 and / or jQuery.

  • Type(<tagname>): Selects elements by their tag name.
  • Descendant(): Selects elements that are descendants of the specified element.
  • Child(>): Selects elements that are direct children of the specified element.
  • Parent (<): Selects elements that are direct parents of the specifiedelement. This follows anold proposalthat has been made obsolete by the:has() pseudo-class.
  • Adjacent sibling(+): Selects elements that are the next sibling of the specified element.
  • General sibling(~): Selects elements that are siblings of the specified element.
  • Attribute([attr=foo]), with supported comparisons:
    • [attr] (existential): Selects elements with the specified attribute,whatever its value.
    • =: Selects elements with the specified attribute and value.
    • ~=: Selects elements with the specified attribute and value, separatedby spaces.
    • |=: Selects elements with the specified attribute and value, separatedby hyphens.
    • *=: Selects elements with the specified attribute and value, anywhere inthe attribute value.
    • ^=: Selects elements with the specified attribute and value, beginningat the beginning of the attribute value.
    • $=: Selects elements with the specified attribute and value, ending atthe end of the attribute value.
    • !=: Selects elements with the specified attribute and value, not equalto the specified value.
    • i ands can be added after the comparison to make the comparisoncase-insensitive or case-sensitive (eg.[attr=foo i]). If neither issupplied, css-select will follow the HTML spec'scase-sensitivity rules.
  • Selector lists(,): Selects elements that match any of the specified selectors.
  • Universal(*): Selects all elements.
  • Pseudos:
    • :not: Selectselements that do not match the specified selector.
    • :contains: Selects elementsthat contain the specified text.
    • :icontains: Selects elements that contain the specified text,case-insensitively.
    • :has: Selectselements that have descendants that match the specified selector.
    • :root: Selectsthe root element.
    • :empty:Selects elements that have no children.
    • :first-child:Selects elements that are the first element child of their parent.
    • :last-child:Selects elements that are the last element child of their parent.
    • :first-of-type:Selects elements that are the first element of their type.
    • :last-of-type:Selects elements that are the last element of their type.
    • :only-of-type:Selects elements that are the only element of their type.
    • :only-child:Selects elements that are the only element child of their parent.
    • :nth-child:Selects elements that are the nth element child of their parent.
    • :nth-last-child:Selects elements that are the nth element child of their parent, countingfrom the last child.
    • :nth-of-type:Selects elements that are the nth element of their type.
    • :nth-last-of-type:Selects elements that are the nth element of their type, counting from thelast child.
    • :any-link:Selects elements that are links.
    • :link: Selectselements that are links and have not been visited.
    • :visited,:hover,:active(these depend on optionalAdapter methods, so these will only matchelements if implemented inAdapter)
    • :checked:Selectsinput elements that are checked, oroption elements that areselected.
    • :disabled:Selects input elements that are disabled.
    • :enabled:Selects input elements that are not disabled.
    • :required:Selects input elements that are required.
    • :optional:Selects input elements that are not required.
    • jQuery extensions:
      • :parent: Selects elementsthat have at least one child.
      • :header: Selects headerelements.
      • :selected: Selectsoption elements that are selected.
      • :button: Selects buttonelements, andinput elements of typebutton.
      • :input: Selectsinput,textarea,select, andbutton elements.
      • :text: Selectsinputelements of typetext.
      • :checkbox: Selectsinput elements of typecheckbox.
      • :file: Selectsinputelements of typefile.
      • :password: Selectsinput elements of typepassword.
      • :reset: Selectsinputelements of typereset.
      • :radio: Selectsinputelements of typeradio.
    • :is, as well asthe aliases:where, andthe legacy alias:matches: Selects elements that match any of the givenselectors.
    • :scope:Selects elements that are part of the scope of the current selector. Thisuses the context from the passed options.

License: BSD-2-Clause

Security contact information

To report a security vulnerability, please use theTidelift security contact. Tidelift willcoordinate the fix and disclosure.

css-select for enterprise

Available as part of the Tidelift Subscription

The maintainers ofcss-select and thousands of other packages are working withTidelift to deliver commercial support and maintenance for the open sourcedependencies you use to build your applications. Save time, reduce risk, andimprove code health, while paying the maintainers of the exact dependencies youuse.Learn more.


[8]ページ先頭

©2009-2025 Movatter.jp