Skip to content

Instantly share code, notes, and snippets.

@kadko
Last active August 28, 2020 19:31
Show Gist options
  • Save kadko/cedbf4ec5ecac97d5ce0621f512eb146 to your computer and use it in GitHub Desktop.
Save kadko/cedbf4ec5ecac97d5ce0621f512eb146 to your computer and use it in GitHub Desktop.
This code finds global DOM tree index of provided element object based on getElementsByTagName tag indexing. It works even if element duplicates exists in DOM. Two different recursive function used so data structure is tree. You can access target element directly resulted index, like this: let element = document.getElementsByTagName("*")[17];
/*
why on Earth i wrote this?
Answer is: if elements has no class, id or other attributes only option is selecting element directly by its index.
*/
let childCount = 0;
let count = 0;
function countTargetChilds(target, firstTarget){
let children = target.children;
if(firstTarget===target){
count = childCount;
}
childCount++;
if(children.length > 0){
[].slice.call(children).forEach((item,index)=>{
return countTargetChilds(item, firstTarget);
});
}
return count;
}
let firstTarget = null;
function moveUpPointer(target, pointer){
if(pointer){ firstTarget = target; }
if( target.tagName === 'HTML' ){
return countTargetChilds(target, firstTarget);
}else{
childCount = 0;
return moveUpPointer(target.parentNode);
}
}
document.addEventListener('click', (e)=>{
let elIndex = moveUpPointer(e.target, true);
let target = document.getElementsByTagName("*")[elIndex];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment