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

折月煮酒 提交于 2019-12-13 02:23:40

问题


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 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]))



回答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.



来源:https://stackoverflow.com/questions/31134087/javascript-get-element-index-position-in-dom-array-by-class-or-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!