How to select even or odd elements based on class name

前端 未结 4 1589
既然无缘
既然无缘 2021-01-23 21:05

if you create html layout like so

4条回答
  •  余生分开走
    2021-01-23 21:47

    The :nth-child pseudo selector looks at the DOM element's (non-zero indexed) index, not within the selected (matching) elements. MooTools added the ':odd' selector to select 'real' odd elements, therefore the index starts at 0.

    So in your example, selecting '.a:nth-child(odd)' will return all li.a elements, because the index starts at 1. Selecting '.a:odd' selects nothing, because there are no 'real' odd li.a elements.

    What you probably want, is to select the ':nth-of-type' element. So selecting '.a:nth-of-type(odd)' would return all odd li.a elements (the first and third one - it uses the DOM element's index).

    MooTools does not support the ':nth-of-type' selector by default, but you can extend the selector engine using the Selectors.Pseudo class (can't find an example right now).

提交回复
热议问题