javascript - 使用javascript的元素的parentNode索引

标签 javascript indexing

假设你有:

<div><p>Some text</p><p>Some text</p></div>
<div><p id='paragraph'>Some text</p></div>

如何使用 javascript 找到 id 'paragraph' 的父节点的索引?我认为您必须使用“docment.getElementsByTagName('div')”进行循环,但之后我就卡住了。感谢您的任何建议。

最佳答案

我假设您只想在索引中包含元素。

var node = document.getElementById('paragraph').parentNode,
    i = 0;

while( node = node.previousSibling ) {
    if( node.nodeType === 1 ) {
        i++;
    }
}

alert(i);

http://jsfiddle.net/dJd6g/

关于javascript - 使用javascript的元素的parentNode索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5998909/

相关文章:

javascript - 如何在 vue.js 中格式化以千、百万或十亿为单位的数字?

javascript - 未捕获的 DOMException : Failed to execute 'addRule' on 'CSSStyleSheet' : Cannot access StyleSheet to insertRule

javascript - 为什么我不能在带有 JavaScript 对象的对象中设置此变量?

indexing - Tinkerpop API 在从 titan 检索数据时不使用混合 Elasticsearch 索引

php - 使用 JavaScript 变量作为索引访问 PHP 数组元素

excel - 使用带有索引的 if 语句

javascript - 在 CasperJS 的 fillSelectors 中使用变量 key

python - 将 2 级索引添加为其他有条件的索引的总和

python NumPy ;冒号和省略号索引之间的区别

javascript - 如何使用 JavaScript 或 JQuery 从 input type=file html 元素获取文件名?