Last active
February 26, 2022 11:29
-
-
Save darsain/7488140 to your computer and use it in GitHub Desktop.
Function that generates element selector hash. Example: div#foo.bar.baz
This file contains 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
function selhash(element) { | |
if (!element || !element.nodeName) { | |
return Object.prototype.toString.call(element) | |
.match(/^\[object (\w+)\]$/i)[1] | |
.toLowerCase() + ':' + element; | |
} | |
var parts = []; | |
parts.push(element.nodeName.toLowerCase()); | |
if (element.id) { | |
parts.push('#' + element.id); | |
} | |
if (element.className) { | |
parts.push('.' + element.className.trim().split(/ +/).join('.')); | |
} | |
return parts.join(''); | |
} |
This file contains 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
<div id="foo" class="bar baz"></div> | |
<script> | |
var element = document.querySelector('#foo'); | |
selhash(element); // div#foo.bar.baz | |
selhash(5); // number:5 | |
selhash(window); // global:[object Window] | |
selhash([1, 2]); // array:1,2 | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment