Skip to content

Instantly share code, notes, and snippets.

@nexpr
Last active February 14, 2016 02:17
Show Gist options
  • Select an option

  • Save nexpr/d705741b5449b9e8e80f to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/d705741b5449b9e8e80f to your computer and use it in GitHub Desktop.
DOMでユニークアクセスできるセレクタ作る
Object.defineProperty(Element.prototype, "index", {
get: function(){
return this.parentElement ?
[].indexOf.call(this.parentElement.children, this)
:
-1
}
})
function createUniqueSelector(elem){
var nths = []
for(;!canUniqueAccess(elem);elem = elem.parentElement){
nths.push(elem.index)
}
return nths.reduceRight((a,b) => a + `>*:nth-child(${b+1})`, getUniqueSelector(elem))
}
function canUniqueAccess(elem){
return elem.id || elem === document.documentElement
}
function getUniqueSelector(elem){
return elem.id ?
"#" + elem.id
:
elem === document.documentElement ?
":root"
:
false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment