How to select even or odd elements based on class name

纵饮孤独 提交于 2019-12-02 07:01:01

问题


if you create html layout like so

<ul>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
     <li class='a'></li>
     <li class='b'></li>
</ul>

and try to select odd elements with 'a' class like so $$('.a:odd') you will get empty array, and if you do $$('.a:even') you will get all four li elements with 'a' class.. It really strange.. But im new to mootools, maybe im doing something wrong..

So my question is how to select first and third li elements with a class. I know that i can do it with function like this

$$('.a').filter(function(item, index) { return index%2; }

but its too complicated for such small task as selecting odd or even elements..


回答1:


The problem is that :odd and :even (and their CSS cousins :nth-child(odd) and :nth-child(even)) refer to the order in which the elements appear as children of their parent, not as children with that particular selector.

This worked for me (Prototype, but it looks like MooTools has similar syntax):

var odd = $$('.a').filter(function(item, index) {
    return index % 2 == 0;
});
var even = $$('.a').filter(function(item, index) {
    return index % 2 == 1;
});

Edit: it seems you already covered that in the question, boo on me for answering before reading fully.




回答2:


If you are trying to get the 1st and third, you just need $$('.a').

Are you trying to get the 1st and 5th items? That would be something like $$('a:nth-child(4n+1))

I am assuming mootools uses css3 Structural pseudo-classes




回答3:


eyelidlessness, so you say it's not a bug? It the way it should work?




回答4:


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).



来源:https://stackoverflow.com/questions/478660/how-to-select-even-or-odd-elements-based-on-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!