Skip to content

Instantly share code, notes, and snippets.

@darsain
Last active February 26, 2022 11:29
Show Gist options
  • Save darsain/7488140 to your computer and use it in GitHub Desktop.
Save darsain/7488140 to your computer and use it in GitHub Desktop.
Function that generates element selector hash. Example: div#foo.bar.baz
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('');
}
<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