-2

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.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Can you please explain why you can't share the code? What does air gapped system have to do with it? – Maik Lowrey Feb 23 '22 at 07:38
  • 1
    It is in a system isnt connected to the internet, and I cannot connect a USB stick (for security reasons basically. I know it is stupid, but it is company policy). – גיא כהן Feb 23 '22 at 07:45
  • Then write some mock-up code? We can't help you without seeing any code – DarkBee Feb 23 '22 at 08:07

3 Answers3

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

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--;
0

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>
Ian
  • 1,198
  • 1
  • 5
  • 15