Last active
August 28, 2020 19:31
-
-
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];
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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