Skip to content

Instantly share code, notes, and snippets.

@heyitsnovi
Created September 28, 2022 03:06
Show Gist options
  • Save heyitsnovi/4d433264e4376623d3033b8eccd7cd6f to your computer and use it in GitHub Desktop.
Save heyitsnovi/4d433264e4376623d3033b8eccd7cd6f to your computer and use it in GitHub Desktop.
Get Element DOM Path
<html>
<head>
<title>Dompath Example</title>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="maindiv">
<a href="#" id="smlink">Some Link</a>
<div class="some-complicated-div">
<div class="some-inner-div">
<span class="hellospan">Hello Span</span>
<span class="hellospan">Hello Clone#1</span>
<span class="hellospan">Hello Clone#2</span>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
function getDomPath(el) {
const stack = []
while (el.parentNode !== null) {
let sibCount = 0
let sibIndex = 0
for (let i = 0; i < el.parentNode.childNodes.length; i += 1) {
const sib = el.parentNode.childNodes[i]
if (sib.nodeName === el.nodeName) {
if (sib === el) {
sibIndex = sibCount
break
}
sibCount += 1
}
}
const nodeName = CSS.escape(el.nodeName.toLowerCase())
// Ignore `html` as a parent node
if (nodeName === 'html') break
if (el.hasAttribute('id') && el.id !== '') {
stack.unshift(`#${CSS.escape(el.id)}`)
// Remove this `break` if you want the entire path
break
} else if (sibIndex > 0) {
// :nth-of-type is 1-indexed
stack.unshift(`${nodeName}:nth-of-type(${sibIndex + 1})`)
} else {
stack.unshift(nodeName)
}
el = el.parentNode
}
return stack.join(' > ');
}
document.addEventListener('click',function(e){
let x = getDomPath(e.target);
alert('Selector For clicked element ==> document.querySelector("'+x+'")');
},false);
</script>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment