Nesting event detection
by Julien Etienne
HTML
<div id="haystack" class="haystack"></div>
CSS
* {
margin-left: 0.001rem;
border: 0.001rem solid red;
box-sizing: border-box;
}
.needle {
background: yellow;
font-size: 5rem;
}
JavaScript
const haystack = document.getElementById('haystack');
const depth = 1500;
let last = haystack;
for (let i = 0; i < depth; i++) {
const div = document.createElement('div');
div.textContent = 'DIV-' + i;
last.appendChild(div);
if (i === depth - 1) {
div.className = 'needle';
}
last = div;
}
// document.addEventListener('click', ({target}) => {
// if (target.className === 'needle') {
// console.time('querySelector');
// const needle = haystack.querySelector('.needle');
// console.log(needle)
// console.timeEnd('querySelector');
// }
// })
const needle = document.getElementsByClassName('.needle').item(0);
document.addEventListener('click', ({target}) => {
if (target.className === 'needle') {
const start = new Date().getMilliseconds();
const needleToHaystack = target.closest('.haystack');
console.log(needleToHaystack)
const end = new Date().getMilliseconds();
alert(end - start )
/// console.timeEnd('closest');
}
})