Skip to content

Javascript get element index position in DOM array by class or id

My situation

var domElements = document.body.getElementsByTagName('*');

Now I want to return the array item key – position of the element in the array – ( for example domElements[34]) searching in the array for the element with id="asd".

How can I achieve this?

What if instead of ID I want to search trough class="asd hey" ?

Any help appreciated, thank you!

NB: Not in jquery, I need it in pure javascript in this case


Try like this

var matches = document.querySelectorAll("#asd");

If you want to search by class

var matches = document.querySelectorAll(".asd");

If you want an index of your code

try like this

var domElements = document.body.getElementsByTagName('*');

for(var i=0;i<domElements.length;i++){
      // search by id 
      // index i 
      // search by class 
      // index i 


There another way you can find index

try like this

var domElements = document.body.getElementsByTagName('*');
var domList='*'));
var itemList =".asd"));
console.log(domList.indexOf(itemList[0])) // if you wanna find one index

//if you wanna search all index of class 

for(var i=0;i<itemList.length;i++)