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

Answer

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++){
   if(domElements[i].id==="asd"){
      // search by id 
      // index i 
   }
   if(domElements[i].className==="asd"){
      // search by class 
      // index i 
   }
}

Edit

There another way you can find index

try like this

var domElements = document.body.getElementsByTagName('*');
var domList= Array.prototype.slice.call(document.body.getElementsByTagName('*'));
var itemList = Array.prototype.slice.call(document.querySelectorAll(".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++)
  console.log(domList.indexOf(itemList[i]))