Get an element's nth-child number in pure JavaScript

前端 未结 5 749
别跟我提以往
别跟我提以往 2020-12-18 20:16

I am making a function for my site where I set a data attribute which contains the nth-child number of that element.

My HTML markup:


<         


        
5条回答
  •  臣服心动
    2020-12-18 20:38

    I'm going to answer the questions with the following assumptions:

    • Your hardware classed elements are all siblings
    • You are interested in nth child not nth child + 1
    • They can be mixed with other elements:
    
        
    some text, nth-child is zero
    some text, nth-child is two

    (I'm making these assumptions, because this is the problem I'm facing, thought it could be useful)

    So the main difference is that instead of querying the elements that belong to a given class, I'm going to get the (direct) children of the body, and filter them.

    Array.from(document.body.children)
      .map((element, index) => ({element, index}))
      .filter(({element}) => element.classList.contains('hardware'))
    

    The resulting array will look like this:

    [
      {element: section.hardware, index: 0}
      {element: section.hardware, index: 2}
    ]
    

提交回复
热议问题