selector-from-element
v1.0.0
Published
Generate a (mostly) unique CSS selector for any DOM node.
Downloads
2
Maintainers
Readme
How to use:
const sel = require('selector-from-element')
var input = document.createElement('input')
input.name = "password"
let form = document.querySelector('body > form#super-form')
form.appendChild(input)
let selector = sel(input)
selector === '#super-form input[name="password"]'
Full code for this package:
function selectorFromNode (node) {
if (node.id) {
return '#' + node.id
}
let tag = node.tagName.toLowerCase()
var special = ''
if (node.name) {
special += `[name="${node.name}"]`
}
var cls = ''
if (!special && node.className) {
cls = node.className.split(/ +/g)
.map(cls => '.' + cls)
.join('')
}
var pos = ''
if (!special) {
var nthoftype = 0
for (let i = 0; i < node.parentNode.children.length; i++) {
let child = node.parentNode.children[i]
if (child.tagName === node.tagName) {
nthoftype++
}
if (node === child) {
pos = `:nth-of-type(${nthoftype})`
break
}
}
}
let sel = tag + special + cls + pos
if (node.parentNode === document.body) {
return 'body > ' + sel
} else {
return `${selectorFromNode(node.parentNode)} > ${sel}`
}
}