Javascript get element index position in DOM array by class or id
Solution 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]))
Solution 2
I think you are asking this:
var li = document.querySelectorAll("li");
function cutlistitem(lielm) {
lielm.addEventListener("click", function () {
lielm.classList.toggle("done")
})
};
li.forEach(cutlistitem);
I was creating a todo list app in which I created an unordered list of tasks to be done, in that <ul>
every task was in an <li>
.
Now what I wanted is: to add an event listener to every li
element for which I needed to grab every element of li
list. I ran a forEach
loop on every element of li
list and added an event listener to each of the element. To get and index of the element you can use indexOf
method.
Solution 3
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.
Comments
-
itsme almost 2 years
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 withid="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