如何获取索引元素?

时间:2016-11-03 18:49:52

标签: javascript

我如何从元素中读取索引?例如:

我有代码:

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

和javascript: var mySpan = document.getElementsByTagName("span")[0]; // it span id="el"没关系,

但我怎么能从这个元素的这个跨度索引中读取

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

3 个答案:

答案 0 :(得分:2)

你说你的意思是它在父母中的位置:为此,计算previousSiblingpreviousElementSibling的次数(取决于你是想要计算其他类型的节点还是只计算元素)不是null

计算所有节点类型:

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>

仅计算元素:

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>

答案 1 :(得分:1)

如果您按getElementById获取元素,则无法进行。您需要引用父项并通过父项子项获取它的索引:

var nodes = Array.prototype.slice.call( document.getElementsByClassName('a')[0].children );
var span = document.getElementById('el');
var index = nodes.indexOf(span);
console.log(index); // 0
var span = document.getElementById('el2');
var index = nodes.indexOf(span);
console.log(index); // 1
<div class="a">
<span id="el">Yeah!</span>
<span id="el2">Yeah!</span>
</div>

答案 2 :(得分:1)

您可以查看父节点及其子节点(使用ES6语法):

const span = document.getElementById("el");
const idx = [...span.parentNode.children].findIndex(n => n === span);

以下是ES5的替代方案:

idx = Array.prototype.slice.call(span.parentNode.children)
  .reduce(function(result, node, i) {
    return node === span ? i : result;
  }, -1);