Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@movable/optimal-select

Autarc24MIT4.2.2

Get efficient & robust CSS selectors for HTML elements

css, path, selector, element

readme

js-standard-style

WARNING: Fork

This is a fork of the main library. Please consider using that instead.

optimal select

A library which creates efficient and robust CSS selectors for HTML elements.

The closest you can get if you're looking for a fingerprint of an HTML element

Features

  • shortest path and fastest selection in comparison
  • configurations allow to define custom options for skip, priority and ignore patterns
  • allows single and multiple element as inputs
  • provide UMD integration (usage via script, AMD or CommonJS)
  • in addition to regular browsers it support the htmlparser2 DOM for virtual environments
  • micro library (~ 11kb, no external dependency)

How To Use

Aside of the prebundled versions the library is also available via npm:

npm install --save optimal-select

Integration

import { select } from 'optimal-select' // global: 'OptimalSelect'

document.addEventListener('click', (e) => {
  var selector = select(e.target)
  console.log(selector)
})

Configuration

By default following attributes are ignored for robustness towards changes:

  • style (inline styles often temporary and used for dynamic visualizations)
  • data-reactid (reacts element identifier which depends on the current DOM structure)
  • data-react-checksum (react string rendered markup which depends on the current DOM structure)

To define custom filters you can pass the 'ignore' property as a secondary optional parameter. You can then specify a validation function for the different types (id, class, attribute, tag).

var selector = select(element, {

  // default reference
  root: document,

  skip (traverseNode) {
    // ignore select information of the direct parent
    return traverseNode === element.parentNode
  },

  // define order of attribute processing
  priority: ['id', 'class', 'href', 'src'],

  // define patterns which should't be included
  ignore: {
    class (className) {
      // disregard short classnames
      return className.length < 3
    },

    attribute (name, value, defaultPredicate) {
      // exclude HTML5 data attributes
      return (/data-*/).test(name) || defaultPredicate(name, value)
    },

    // define simplified ignore patterns as a boolean/string/number/regex
    tag: 'div'
  }
})

As shown the root property allows to define the container element (default: document). The skip value allows to define a function, a single node or an array of nodes which should be ignored as the selector is created (default: null). With the priority value can the order of processed attributes be customized. Finally individual filter functions can be defined through ignore.

API

  getQuerySelector (input, [options]) // alias: 'select'

Convenience function which automatically uses either getSingleSelector or getMultiSelector

  getSingleSelector(element, [options])

Retrieve a unique CSS selector of the element Element is a DOM ode

  getMultiSelector(elements, [options])

Retrieve a unique CSS selector of the elements Elements is an array with a list of DOM nodes

  optimize(selector, elements, [options])

Improve the CSS selector

  getCommonAncestor(elements, [options])

Retrieve the closest ancestor of the elements

  getCommonProperties(elements, [options])

Retrieve a set of common properties of the elements

Client & Server

The latest version of optimal-select allows the generation and optimization of selectors on virtual environments. It uses the basic structure the htmlparser2 DOM provides and adds some utilities to create the same results as the browser (note: the withDOMLv1 option has to be enabled). Other libraries like cheerio are built on top of these and therefore compatible.

In contrast to the browser does server environments not have a global context which defines their scope. Therefore one can either be specified explicit through a node using the context options field or automatically extracted from the provided input element. Checkout the example for more details.

TODO

  • extend documentation
  • add automatic tests (e.g. using jsdom)
  • improve child-relation and grouping of getMultiSelector
  • define strict option for optimizations of multiple elements
  • check attributes for complex classnames
  • fix #8 - Full coverage for "nth-of-type" optimization
  • consider :not - selector to exclude other elements matching (for multiple element matching consider the :not selector to exclude exceptions)

Development

To build your own version run npm run dev for development (incl. watch) or npm run build for production (minified).

changelog

[v4.0.1]

January, 07, 2017

  • fix invalid selector query in partial classname optimization
  • fix match check of regex in complex classname optimization

[v4.0.0]

December 29, 2016

  • change default behavior of checking attributes
  • use general selector instead of wildcard fallback
  • allow boolean for ignore pattern definitions
  • upgrade built tools and exclude the adapter in distributed versions
  • fix invalid class and id selectors through regular attributes
  • fix invalid selectors for values which include line breaks
  • fix array checking in getQuerySelector(based on #23, by @kasperisager)

[v3.5.0]

November 11, 2016

  • fix escape of selector values
  • allow defining the order to process attributes
  • optimize chunks of short selectors

[v3.4.3]

November 8, 2016

[v3.4.1]

November 5, 2016

  • fix public API exports

[v3.4.0]

November 4, 2016

  • enable optimization for selectors of multiple elements

[v3.3.1]

October 28, 2016

  • fix check for available class attribute

[v3.3.0]

October 7, 2016

  • fix missing pass options to getSingleSelector (#16, by @Zhuoqing)
  • fix optimization of child selectors with multiple classnames
  • apply optimizations on simple selectors
  • add default options and parameter checks for public API
  • improve getMultiSelector for matching nested descendants

[v3.2.0]

June 18, 2016

  • add options.skip to allow the definition of elements which shouldn't be considered
  • use name fallback for the ignore predicate function of class

[v3.1.0]

May 18, 2016

  • add options.root to allow the definition of the container element

[v3.0.0]

Apr 15, 2016

  • add support for virtual representations based on the htmlparser2 DOM

[v2.2.0]

Apr 02, 2016

  • improve whitespace matching in classnames (#6 by @paulborges)
  • enable simplified ignore patterns based on strings/regex
  • fix matching ignored classes as attributes

[v2.1.0]

Mar 08, 2016

  • change options.excludes to options.ignore and allow the definitions of flexible predicate functions to ignore specific pattern matches

[v2.0.2]

Mar 07, 2016

  • fix splitting of select segments in case attribute values contain spaces
  • lookup the class attribute instead of the className property to support svg elements

[v2.0.1]

Jan 24, 2016

  • replace element validation to remove implicit dependency on global window

[v2.0.0]

Jan 15, 2016

  • enable filtering with RegExp to exclude specific property values
  • replace complex key-value and classname selectors with tags

[v1.0.2]

Jan 2, 2016

  • add example
  • reference pre-built files
  • replace NodeList iteration with regular for-loop
  • module exports 'select' as default
  • ignore 'data-react-checksum' attribute by default

[v1.0.1]

Dec 11, 2015

  • add .npmignore

[v1.0.0]

Dec 10, 2015

  • initial release