【发布时间】:2020-12-17 01:36:16
【问题描述】:
我希望能够引用 HTML DOM 中的任何元素,并且还知道元素出现的顺序。我希望 DOM 中的元素被索引到从 0 到
例如,在这个 HTML 中,元素的编号从 html 元素的 0 到第二个 p 元素的 9:
<html lang="en-US">
<head>
<title>Element 2. Page title</title>
</head>
<body>
<h1 id="mainHead">Element 4. How to uniquely identify/order DOM elements</h1>
<div id="boxedContent">
<p class="smallText">Element 6. I want to be able to <span class="stress">7. uniquely</span> identify each element and <i>8. also</i> determine the order in which elements appear, reading from top to bottom through the HTML.</p>
</div>
<p>Element 9</p>
</body>
</html>
我想要一种 JavaScript/jQuery 方式来指定,例如,title 元素、第一个 p 元素和 span。我将使用的 HTML 页面不是我的,但如果有我可以访问的整个 DOM 元素索引,我可以使用这些索引引用来访问这 3 个元素 - 即
- 标题:2
- 第一页:6
- 跨度:7
索引号可以让我按顺序列出元素。
这可能吗?我该怎么做?
【问题讨论】:
-
$('selector').index('*')??? api.jquery.com/index -
这给出了相对于兄弟 $('selector') 元素的索引。我正在寻找所有元素的索引,从上到下贯穿 DOM。
-
不,它返回相对于传递给
index()方法的选择器的索引:If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.
标签: javascript jquery dom