Skip to content

Instantly share code, notes, and snippets.

@creotiv
Created December 14, 2012 19:20
Show Gist options
  • Save creotiv/4287903 to your computer and use it in GitHub Desktop.
Save creotiv/4287903 to your computer and use it in GitHub Desktop.
Geting XPath of selected DOM element and highlighting it
function getPathTo(element) {
if (element.id!=='')
return 'id("'+element.id+'")';
if (element===document.body)
return element.tagName;
var ix= 0;
var siblings= element.parentNode.childNodes;
for (var i= 0; i<siblings.length; i++) {
var sibling= siblings[i];
if (sibling===element)
return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
if (sibling.nodeType===1 && sibling.tagName===element.tagName)
ix++;
}
}
function getBody(element) {
if(element.tagName == 'DIV')
return element;
if (element===document.body)
return element;
return getBody(element.parentNode);
}
function selectTargetToParse(e) {
if (!e) var e = window.event;
var tg = (window.event) ? e.srcElement : e.target;
alert(tg.tagName);
document.body.onmousedown = null;
document.body.onmouseover = null;
document.body.onmouseout = null;
tg.className = tg.className.replace( /(?:^|\s)bot-parser-selected(?!\S)/g , '' );
}
function lightTargetToParse(e) {
if (!e) var e = window.event;
var tg = (window.event) ? e.srcElement : e.target;
tg.className += ' bot-parser-selected ';
}
function unlightTargetToParse(e) {
if (!e) var e = window.event;
var tg = (window.event) ? e.srcElement : e.target;
tg.className = tg.className.replace( /(?:^|\s)bot-parser-selected(?!\S)/g , '' );
}
var style = document.createElement('style');
style.type = 'text/css'
style.innerHTML = '.bot-parser-selected {position:relative;} .bot-parser-selected:after {content: "";position: absolute;top: 0;right: 0;background: #245991;opacity: 0.5;width:100%;height:100%;}';
document.getElementsByTagName('head')[0].appendChild(style)
document.body.onmousedown = selectTargetToParse;
document.body.onmouseover = lightTargetToParse;
document.body.onmouseout = unlightTargetToParse;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment