Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including csstoxpath with all npm packages installed. Try it out:

var csstoxpath = require("csstoxpath")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

csstoxpath v1.4.0

CSS to XPath

Build Status

CSS to XPath

Converts most CSS 2.1/3 selectors (see exclusions below) to equivalent XPath 1.0 expression.

See test.js for examples.

Extension pseudos

To take advantage of the different capabilities of XPath some additional pseudo selectors have been implemented:

:text

All text matching pseudo classes normalize whitespace and ignore tags. E.g. " my <i>string</i> " is treated as "my string".

  • :text("foo") Case-insensitive matching of element text
  • :text-case("foo") Case-sensitive :text-case
  • :text-contains("foo") Case-insensitive substring matching of element text
  • :text-contains-case("foo") Case-sensitive :text-contains
  • :text-start("foo") Case-insensitive matching of element starting text
  • :text-start-case("foo") Case-sensitive :text-start
  • :text-end("foo") Case-insensitive matching of element ending text
  • :text-end-case("foo") Case-sensitive :text-end

:any

Selectors containing multiple options, any one of which will be matched:

E.g: div :any(ol, ul, dl) > * equates to div ol > *, div ul > *, div dl > *

:comment

  • :comment Select comment nodes
  • :comment(n) Select comment nodes at child position n

Note: Can be combined with :text to match based on comment text content. E.g. p > :comment:text("foo")

:childless

As :empty but ignoring whitespace.

Author pseudos

Authored pseudos can serve as aliases to help simplify selector chains:

/*
 * If the `pseudos` option is set the CSS expression is
 * preprocessed before generating the XPath expression.
 * In this case as follows:
 *
 * before  :radio:nth(2)
 * after   input[type="radio"]:nth-child(2)
 */
const cssToXpath = require('csstoxpath');
const xpathExpr = cssToXpath(':radio:nth(2)', {
    pseudos: {
        radio: 'input[type="radio"]',
        nth: data => `:nth-child(${data})`,
    }
});

Unsupported psuedos

The following may be supported at a later date:

  • :nth-last-child

Part-dynamic pseudos are excluded as they can only be partially supported by attribute matching:

  • :checked
  • :disabled
  • :enabled
  • :required
  • :lang

The following cannot be implemented in XPath 1.0:

  • :*-of-type
  • States: :hover, :focus, :active, :visited, :target etc.
  • Elements: ::before, ::after, ::first-letter etc.

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free