JSPM

selector-from-element

1.0.0
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 2
    • Score
      100M100P100Q25756F
    • License MIT

    Generate a (mostly) unique CSS selector for any DOM node.

    Package Exports

    • selector-from-element

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (selector-from-element) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    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}`
      }
    }