Link to sectionExample
Obtain array of parent elements when hovering/clicking an element
by larsolesimonsen
HTML
<div id="box1" style="height: 100px; width: 100px;background: gray;">
<div id="box11" style="height: 30px; width: 30px; background: #aaa;">
<div id="box111" style="height: 10px; width: 10px; background: #ccc;">
</div>
</div>
<div id="box12" style="height: 30px; width: 30px; background: #bbb;">
</div>
</div>
<br>
<br>
<div id="box2" style="height: 100px; width: 100px;background: gray;">
<div id="box21" style="height: 30px; width: 30px; background: #bbb; position: relative; left: 200px;">
rel
</div>
<div id="box22" style="height: 30px; width: 30px; background: #ccc; position: absolute; left: 300px;">
abs
</div>
</div>
<br>
<br>
<pre id="output">
</pre>
<div style="position: fixed; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 10000; top: 0; left: 0; pointer-events: none;">
</div>
JavaScript
function pathFromPathObjects(pathObjects) {
return pathObjects.map(function(o) {
return (o.id ? '#' + o.id : '') || (o.classes.length ? '.' + o.classes[0] : '') || (o.attributes.length ? o.attributes[0].name + '[' + o.attributes[0].value + ']' : '') || o.tagName;
}).join('/');
}
function toArr(a) {
return Array.prototype.slice.call(a)
}
var counter = 0;
function handleClick(e) {
var pathElts = document.querySelectorAll(':hover');
var pathObjects = toArr(pathElts).filter(function(p) {
return p.tagName !== 'HTML' && p.tagName !== 'BODY';
}).map(function(p) {
return {
tagName: p.tagName,
classes: p.className.split(' ').filter(function(x) { return x; }),
id: p.id,
attributes: toArr(p.attributes)
.filter(function(a) { return a.name !== 'class' && a.name !== 'id'; })
.map(function(a) { return { name: a.name, value: a.value }; })
}
});
var path = pathFromPathObjects(pathObjects);
var output = counter++ + ' events\npath ' + path + '\n' + JSON.stringify(pathObjects, null, 2)
document.querySelector('#output').innerHTML = output;
stopEvent(e);
}
function stopEvent(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
}
// React to button being pressed by user
document.body.addEventListener('click', handleClick, true);
document.body.addEventListener('mouseover', handleClick, true);
['mousedown', 'mouseup', 'mouseenter', 'mouseleave'].forEach(function (e) {
document.body.addEventListener(e, stopEvent, true);
});
document.querySelector('#box1').addEventListener('mouseup', function(e) {
alert('box 1 clicked');
});