[英]How to get nth number of an element child in js
i have this html:我有这个 html:
<div id="helo">
<span id="hjhn">sample text</span>
<span id="uhed">melaps xtet</span>
<span id="kdhs">elpmas txet</span>
</div>
then i need something that you tell the id and it returns the number of the element.然后我需要一些你告诉 id 的东西,它返回元素的编号。
so for example:例如:
helo('#hjhn'); // Output: 0
helo('#uhed'); // Output: 1
helo('#kdhs'); // Output: 2
I've tried a lot of like 3 different ways but I just dont know how, so it would be great that you'd try to help me!我已经尝试了很多类似 3 种不同的方法,但我只是不知道如何,所以如果你能帮助我就太好了!
You could do something like this.你可以做这样的事情。
const parent = document.querySelector("#helo");
const getChildIndex = (_id) => {
let index = 0;
for (const child of parent.children) {
index++;
if (child.id === _id){
return index;
}
}
}
console.log(getChildIndex("kdhs"))
The main goal is to loop through the child elements and map them to an index number.主要目标是遍历子元素并将它们 map 循环到一个索引号。 It can be done in various ways.
它可以通过多种方式完成。
Yes, there are a number of ways to do this.是的,有很多方法可以做到这一点。 Here's another.
这是另一个。
function getSpanIndex(id) {
const div = document.getElementById('helo');
const spans = div.querySelectorAll('span');
for (let i = 0; i < spans.length; ++i) {
if (spans[i].id === id)
return i;
}
return -1;
}
The Following function is flexible in places where you don't know the parent of the selected element.以下 function 在您不知道所选元素的父级的地方很灵活。
const getIndex = (id) => {
const c = document.getElementById(id);
const parent = c.parentNode;
return Array.from(parent.children).findIndex((i) => i.id == id);
};
console.log(getIndex("uhed"));
It selects an element with the given id and loops through the children of the parent of the selected element.它选择具有给定 id 的元素并循环遍历所选元素的父元素的子元素。
Additionally, you can add if statements to check whether c
is undefined to avoid run time errors in cases where an element with the given id doesn't exist in the DOM.此外,您可以添加 if 语句来检查
c
是否未定义,以避免在 DOM 中不存在具有给定 id 的元素时出现运行时错误。
Template string can be well done:模板字符串可以很好地完成:
function test(ele) {
const currentEle = document.querySelector(`${ele}`);
return Array.from(currentEle.parentNode.children).findIndex(item => item === currentEle);
}
You can use the querySelector function for selecting nth-child.您可以使用 querySelector function 来选择第 n 个孩子。 See the below example.
请参见下面的示例。
const document = document.querySelector('#helo span:nth-child(2)');
console.log(document); // 👉️ <span id="kdhs">elpmas txet</span>
Note: nth-child( 2 ) this "2" is the index of your item.注意:第 nth-child( 2 ) 这个“2”是你的项目的索引。 It starts from 0
它从0开始
Check this blog for more details - https://bobbyhadz.com/blog/javascript-get-nth-child-of-element查看此博客了解更多详情 - https://bobbyhadz.com/blog/javascript-get-nth-child-of-element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.