Mankament Gra Mankament Gra - 1 month ago 8
Javascript Question

How to get index element?

How i can read index from element? example:

I have code:

<div class="a">
<span id="el">Yeah!</span>
<span class="span">1</span>
<span class="span">2MANO</span>
</div>


and javascript:
var mySpan = document.getElementsByTagName("span")[0]; // it span id="el"
its ok,

but how i can read from this span index of this element

var span= document.getElementById("el"); // i should get index 0 but i cant do that

Answer

You've said you mean its position within its parent: To do that, count how many times previousSibling or previousElementSibling (depending on whether you want to count other kinds of nodes or just Elements) is not null:

Counting all node types:

function getIndex(node) {
  var index = 0;
  while (node.previousSibling) {
    node = node.previousSibling;
    ++index;
  }
  return index;
}
console.log(getIndex(document.getElementById("el")));  // 0
console.log(getIndex(document.getElementById("el2"))); // 5, counts text nodes
<div class="a">
<span id="el">Yeah!</span>
<span class="span">1</span>
<span class="span" id="el2">2MANO</span>
</div>

Counting only elements:

function getElementIndex(node) {
  var index = 0;
  while (node.previousElementSibling) {
    node = node.previousElementSibling;
    ++index;
  }
  return index;
}
console.log(getElementIndex(document.getElementById("el")));  // 0
console.log(getElementIndex(document.getElementById("el2"))); // 2, counts only elements
<div class="a">
<span id="el">Yeah!</span>
<span class="span">1</span>
<span class="span" id="el2">2MANO</span>
</div>

Comments