'How I find the position of an HTML element [closed]
I am working on a project where I need to find the position of a "div" element, relative to the other divs (index position). for example if I have a div of class "item" and below it a div of class "list", the "item" would have an index value of 0, and the "list" would have an index value of 1.
I need help in finding the divs index.
I also need to use vanilla javascript without any library and no jQuery
I would share the code but unfortunatly, I write the program on an air gapped system. so I cannot post the code here.
Solution 1:[1]
You can fetch all divs and iterate the List. Check if contains the classes item or list and push to an array the index.
for example like that:
const d = document.querySelectorAll('div');
let r = [];
for(let i = 0; i < d.length; i++) {
if (d[i].classList.contains('item')) {
r.push({'itemIndex': i});
}
if (d[i].classList.contains('list')) {
r.push({'listIndex': i});
}
};
console.log(r)
<div class="a">A</div>
<div class="x">X</div>
<div class="item">ITEM</div>
<div class="list">LIST</div>
<div class="y">Y</div>
Solution 2:[2]
After much digging I found this post: JavaScript DOM: Find Element Index In Container
which my answer is based of (note the objects are inside a div called wit a class of "side-bar" and the amount of divs is saved in a global variable called sidebar_len)
var element1 = el_in; //the function gets "this" for the event
var sidebar = document.getElementsByClassName("side-bar")[0];
var sidebar_divs = sidebar.getElementsByTagName("div");
var div_index = 0;
var is_same = false;
while(div_index < sidebar_len && is_same == false) {
is_same = sidebar_divs[div_index].isSameNode(element1);
div_index++
}
div_index--;
Solution 3:[3]
const index = (start, find) => {
const sEl = document.getElementsByClassName(start)[0];
const el = document.getElementsByClassName(find)[0];
const childrens = [...el.parentElement.children];
const sIndex = childrens.indexOf(sEl);
for (let i = sIndex - 1; i >= 0; i--) {
childrens.splice(i, 1);
}
return childrens.indexOf(el);
};
const startClsName = 'item';
console.log('item index', index(startClsName, 'item'));
console.log('list index', index(startClsName, 'list'));
<div class='first'></div>
<div class='second'></div>
<div class='item'></div>
<div class='list'></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maik Lowrey |
| Solution 2 | |
| Solution 3 | Ian |
