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

JavaScript object that creates unique CSS selector for given element.

License

NotificationsYou must be signed in to change notification settings

fczbkk/css-selector-generator

Repository files navigation

JavaScript object that creates a unique CSS selector for a given DOM element or multiple DOM elements.

It also generates shorter selectors and is faster and/or more robust than many other libraries - see thiscomparison and select the best alternative for your use case.

Install

Add the library to your project via NPM or Yarn.

npm install css-selector-generatoryarn add css-selector-generator

Then include it in your source code:

import{getCssSelector}from"css-selector-generator";

How to use

Simplest way to use it is to provide an element reference, without any options.

<body><!-- targetElement --><divclass="myElement"></div></body>
getCssSelector(targetElement);// ".myElement"

Typical example is to create a selector for any element that the user clicks on:

// track every clickdocument.body.addEventListener("click",function(event){// get reference to the element user clicked onconstelement=event.target;// get unique CSS selector for that elementconstselector=getCssSelector(element);// do whatever you need to do with that selectorconsole.log("selector",selector);});

Usage without NPM

If you don't want to use this library with NPM, you can download it directly from the "build" folder and insert it to your HTML document directly. In this case, the library is wrapped in namespaceCssSelectorGenerator. So the usage would look something like this:

<!-- link the library --><scriptsrc="build/index.js"></script><script>CssSelectorGenerator.getCssSelector(targetElement)</script

Usage with virtual DOM (e.g. JSDOM)

If you want to use this library with Node, usually for testing, don't require it directly into the Node process. It will not work, because there's nowindow object and there are no elements to select. Instead, you have to add the library to the virtualwindow object. Here are instructions how to do it in JSDOM, other libraries will work in a similar way:https://github.com/jsdom/jsdom/wiki/Don't-stuff-jsdom-globals-onto-the-Node-global

Multi-element selector

This library also allows you to create selector targeting multiple elements at once. You do that by calling the same function, but you provide an array of elements instead of single element:

<body><!-- firstElement --><divclass="aaa bbb"></div><!-- secondElement --><spanclass="bbb ccc"></span></body>
getCssSelector([firstElement,secondElement]);// ".bbb"

If it is not possible to construct single selector for all elements a standalone selector for each element will be generated:

<body><!-- firstElement --><div></div><!-- secondElement --><span></span></body>
getCssSelector([firstElement,secondElement]);// "div, span"

Fallback

getCssSelector determines the shortest CSS selector for parent -> child relationship, from the input Element until the Root Element.

If there is nounique selector available for any of these relationships (parent -> child), a fallback of* will be used for this relationship.

#wrapper > * > div > .text

In some cases, this selector may not be unique (e.g.#wrapper > * > div > *). In this case, it will fall back to an entire chain of:nth-child selectors like:

":nth-child(2) > :nth-child(4) > :nth-child(1) > :nth-child(12)"

Options

Selector types

You can choose which types of selectors do you want to use:

<body><!-- targetElement --><divclass="myElement"></div></body>
getCssSelector(targetElement,{selectors:["class"]});// ".myElement"getCssSelector(targetElement,{selectors:["tag"]});// "div"

Order of selector types defines their priority:

getCssSelector(targetElement,{selectors:["class","tag"]});// ".myElement"getCssSelector(targetElement,{selectors:["tag","class"]});// "div"

Valid selector types are:

  • id
  • class
  • tag
  • attribute
  • nthchild
  • nthoftype

Root element

You can define root element, from which the selector will be created. If root element is not defined, document root will be used:

<body><divclass="myRootElement"><!-- targetElement --><divclass="myElement"></div></div></body>
getCssSelector(targetElement);// ".myRootElement > .myElement"getCssSelector(targetElement,{root:document.querySelector(".myRootElement"),});// ".myElement"

Blacklist

If you want to ignore some selectors, you can put them on the blacklist. Blacklist is an array that can contain either regular expressions, strings and/or functions.

Instrings, you can use an asterisk (*) as a wildcard that will match any number of any characters.

Functions will receive a selector as a parameter. They should always return boolean,true if it is a match,false if it is not. Any other type of return value will be ignored.

<body><!-- targetElement --><divclass="firstClass secondClass"></div></body>
getCssSelector(targetElement,{blacklist:[".firstClass"]});// ".secondClass"getCssSelector(targetElement,{blacklist:[".first*"]});// ".secondClass"getCssSelector(targetElement,{blacklist:[/first/]});// ".secondClass"getCssSelector(targetElement,{blacklist:[(input)=>input.startsWith(".second")],});// ".secondClass"

You can target selectors of any types using the blacklist.

getCssSelector(targetElement,{blacklist:[// ID selector"#forbiddenId",// class selector".forbiddenClass",// attribute selector"[forbidden-attribute]",// tag selector"div",],});

Whitelist

Same asblacklist option, but instead of ignoring matching selectors, they will be prioritised.

<body><!-- targetElement --><divclass="firstClass secondClass"></div></body>
getCssSelector(targetElement,{whitelist:[".secondClass"]});// ".secondClass"getCssSelector(targetElement,{whitelist:[".second*"]});// ".secondClass"getCssSelector(targetElement,{whitelist:[/second/]});// ".secondClass"

Combine within selector

If set totrue, the generator will try to look for combinations of selectors within a single type (usually class names) to get better overall selector.

<body><!-- targetElement --><divclass="aaa bbb"></div><divclass="aaa ccc"></div><divclass="bbb ccc"></div></body>
getCssSelector(targetElement,{combineWithinSelector:false});// "body > :nth-child(1)" - in this case no single class name is uniquegetCssSelector(targetElement,{combineWithinSelector:true});// ".aaa.bbb"

This option is set totrue by default. It can be set tofalse for performance reasons.

Combine between selectors

If set totrue, the generator will try to look for combinations of selectors between various types (e.g. tag name + class name) to get better overall selector.

<body><!-- targetElement --><divclass="aaa"></div><divclass="bbb"></div><pclass="aaa"></p></body>
getCssSelector(targetElement,{combineBetweenSelectors:false});// "body > :nth-child(1)" - in this case no single class name or tag name is uniquegetCssSelector(targetElement,{combineBetweenSelectors:true});// "div.aaa"

This option is set totrue by default. It can be set tofalse for performance reasons.

Include tag

This option will add tag selector type to every selector:

<body><!-- targetElement --><divclass="myElement"></div></body>
getCssSelector(targetElement,{includeTag:true});// "div.myElement"

Max combinations

This is a performance optimization option that can help when trying to find a CSS selector within elements that contain large numbers of class names (e.g. because of frameworks that create atomic styles) or other attributes.

In such case, the number of possible combinations between class names can be too large (it grows exponentially) and can significantly slow down selector generation. In reality, if the selector is not found within first few combinations, it usually won't be found within the rest of combinations.

getCssSelector(targetElement,{maxCombinations:100});

Max candidates

Performance optimization option, similar tomaxCombinations. This does limit a total number of selector candidates for each element.

You should use it in cases, when there are not too many class names and attributes, but they are numerous enough to produce large number of combinations between them.

getCssSelector(targetElement,{maxCandidates:100});

Use scope

Experimental feature -This will probably be turned on by default and the option will be removed, after I thoroughly evaluate that it produces valid selectors in all use cases.

If set totrue and theroot option is provided, the fallback selectors will be created relative to theroot element using the:scope pseudo-class.

For example, if you have the following HTML structure:

<html><body><div><div><!-- haystackElement --><div><div><!-- needleElement --></div></div></div></div></body></html>

If you generate the selectorwithout theuseScope option:

getCssSelector(needleElement,{root:haystackElement,useScope:false,});

...it will produce this fallback selector:

:root > :nth-child(1) > :nth-child(1) > :nth-child(1) > :nth-child(1) > :nth-child(1)

... where the selectors correspond with these elements:

:root             -> <html>> :nth-child(1)   ->   <body>> :nth-child(1)   ->     <div>> :nth-child(1)   ->       <div> <!-- haystackElement -->> :nth-child(1)   ->         <div>> :nth-child(1)   ->           <div> <!-- needleElement -->

But if you generate the selectorwith theuseScope option:

getCssSelector(needleElement,{root:haystackElement,useScope:true,});

...it will produce this fallback selector:

:scope > :nth-child(1) > :nth-child(1)

... where the selectors correspond with these elements:

:scope            -> <div> <!-- haystackElement -->> :nth-child(1)   ->   <div>> :nth-child(1)   ->     <div> <!-- needleElement -->

Bug reports, feature requests and contact

If you found any bugs, if you have feature requests or any questions, please, eitherfile an issue on GitHub or send me an e-mail atriki@fczbkk.com

License

CSS Selector Generator is published under theMIT license.

About

JavaScript object that creates unique CSS selector for given element.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors10


[8]ページ先頭

©2009-2025 Movatter.jp