Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created December 28, 2016 12:17
Show Gist options
  • Save andreasvirkus/25c612aac704ec00ac75c5fa3f14f4a6 to your computer and use it in GitHub Desktop.
Save andreasvirkus/25c612aac704ec00ac75c5fa3f14f4a6 to your computer and use it in GitHub Desktop.
// ES5
function getNodeindex( elm ){
var c = elm.parentNode.children, i = 0;
for(; i < c.length; i++ )
if( c[i] == elm ) return i;
}
// ES6
function getNodeindex( elm ){
return [...elm.parentNode.children].findIndex(c => c == elm)
// or
return [...elm.parentNode.children].indexOf(elm)
}
// Usage with the following HTML
// <body>
// <nav></nav>
// <header></header>
// <footer></footer>
// </body>
let el = document.getElementById('header');
getNodeindex(el); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment