Home > Net >  How to get nth number of an element child in js
How to get nth number of an element child in js

Time:01-31

i have this 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.

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!

CodePudding user response:

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. It can be done in various ways.

CodePudding user response:

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;
}

CodePudding user response:

The Following function is flexible in places where you don't know the parent of the selected element.

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.

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.

CodePudding user response:

`Template string can be well done

function test(ele){
      const currentEle = document.querySelector(`${ele}`)
      return Array.from(currentEle.parentNode.children).findIndex(item => item === currentEle)
}

CodePudding user response:

You can use the querySelector function for selecting nth-child. See the below example.

const document = document.querySelector('#helo span:nth-child(2)');
console.log(document); //            
  • Related