[英]Get an element's nth-child number in pure JavaScript
我正在為我的網站制作一個 function,我在其中設置了一個包含該元素的第 n 個子編號的數據屬性。
我的 HTML 標記:
<html>
<body>
<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>
</body>
</html>
到目前為止,我的 JavaScript:
var selector = document.getElementsByClassName('hardware');
for(var i = 0; i <= selector.length; i++) {
var index = selector[i] //get the nth-child number here
selector[i].dataset.number = index;
}
如何使用純 JavaScript(不是 jQuery)獲取元素的第 n 個子編號,這在 JavaScript 中是否可行?
在這里查看以前的答案。
它用
var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.
當你說“數字”時,你的意思是1,2等,還是“一個”,“兩個”等?
如果是1,2等,那么數字就是i + 1 ......
如果“one”,“two”等,那么你需要獲取元素內的文本,然后可能使用Regexp來解析它並獲得你想要的值。
簡單地線性遞增索引只有在匹配該類名的所有元素都是同一父級的唯一子元素時才有效,沒有其他元素可以干擾:nth-child()
,如給定標記中所示。 請參閱此答案 ,了解其他元素可能會如何干擾。 還要查看選擇器規范 :nth-child()
。
實現這一目標的一種方法更加簡單,就是遍歷每個元素父節點的子節點,為每個作為元素節點的子節點遞增一個計數器(因為:nth-child()
只計算元素節點):
var selector = document.getElementsByClassName('hardware');
for (var i = 0; i < selector.length; i++) {
var element = selector[i];
var child = element.parentNode.firstChild;
var index = 0;
while (true) {
if (child.nodeType === Node.ELEMENT_NODE) {
index++;
}
if (child === element || !child.nextSibling) {
break;
}
child = child.nextSibling;
}
element.dataset.number = index;
}
請注意, 無論給定元素在DOM中的位置如何 ,這都將應用正確的索引:
如果特定的section.hardware
元素是不同section
的第一個也是唯一的子section.hardware
,則會為其指定正確的索引1。
如果.hardware
元素是.hardware
元素的第二個子元素,即使它是唯一具有該類的子元素(即它跟隨一個沒有該類的其他元素),它也將被賦予正確的索引2。
我將用以下假設回答這些問題:
hardware
分類元素都是兄弟姐妹 <body>
<section class="hardware">some text, nth-child is zero</section>
<section class="software"></section>
<section class="hardware">some text, nth-child is two</section>
</body>
(我正在做這些假設,因為這是我面臨的問題,認為它可能有用)
所以主要區別在於,我不是要查詢屬於給定類的元素,而是要獲取body
的(直接)子元素,並對其進行過濾。
Array.from(document.body.children)
.map((element, index) => ({element, index}))
.filter(({element}) => element.classList.contains('hardware'))
結果數組將如下所示:
[
{element: section.hardware, index: 0}
{element: section.hardware, index: 2}
]
您可以在空格處拆分文本,從每個拆分數組中獲取最后一個單詞 :
var hards = document.getElementsByClassName('hardware');
for (var i=0; i < hards.length; i++) {
var hardText = hards[i].innerText || hard[i].textContent;
var hardList = hardText.split(' ');
var hardLast = hardList[hardList.length - 1];
alert(hardLast);
}
我正在使用|| 這里因為Firefox不支持innerText
,而IE不支持textContent
。
如果元素只包含文本,則可以使用innerHTML
而不是innerText/textContent
。
[].slice.call(elem.parentElement.childNodes).indexOf(elem)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.