Javascript get element index position in DOM array

2019-08-05 13:19发布

问题:

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

回答1:

Try like this

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

If you wanna search by class

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

If you wanna 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]))


回答2:

Not literal code but if you iterate over the dom elements

for (var i = 0; i < parentElement.children.length; i++) {
    var item = parentElement.children[i];
    if (item.getAttribute('id') === 'asd') {
        return i;
    }
}

This has the assumption that instead of selecting ALL DOM elements, you simply select the parentElement of your list of elements - this approach is more logical and certainly a lot more efficient.