Last active
February 14, 2016 02:17
-
-
Save nexpr/d705741b5449b9e8e80f to your computer and use it in GitHub Desktop.
DOMでユニークアクセスできるセレクタ作る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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