1.0.3 • Published 7 months ago
selector-ranker v1.0.3
Selector Ranker
A lightweight utility to generate and rank CSS selectors for a DOM element by specificity. Useful for debugging, testing, or identifying the most specific selector for any given element.
Features
- Generates ranked CSS selectors:
- ID-based selectors
- Class-based selectors
- Full-path selectors
- Works with any valid DOM element.
- No dependencies.
Installation
Install via npm:
npm install selector-ranker
Usage
In Node Js
const rankSelectors = require('selector-ranker');
const { JSDOM } = require('jsdom');
// Simulate a DOM environment
const dom = new JSDOM(`<!DOCTYPE html><div id="test" class="foo bar"></div>`);
const element = dom.window.document.getElementById('test');
// Generate selectors
const selectors = rankSelectors(element);
console.log(selectors);
// Output: ['#test', '.foo.bar', 'html body div#test.foo.bar']
In Browser
1.Include the index.js file in your project and use it as a module:
<script type="module">
import { rankSelectors } from './index.js';
const element = document.getElementById('my-element');
console.log(rankSelectors(element));
</script>
2.The output will be an array of selectors ranked from most specific to least specific.
API
rankSelectors(element)
Parameters:
element
(required): A valid DOM element.
Returns:
Array<string>
: A list of ranked CSS selectors for the given element.
Example Output
For the following HTML:
<div id="parent" class="container">
<div id="child" class="box special">Hello!</div>
</div>
The output for #child
element will be :
[
'#child',
'.box.special',
'html body div.container div#child.box.special'
]