I’ve got a variable, let’s call it $listObjects. The data of it is as followed….
<li>Data Here 1</li>
<li>Data Here 2</li>
<li>Data Here 3</li>
<li>Data Here 4</li>
I have tried every way I can think of, and can’t find out how to get the nth-child of the list tags. Is this possible? I basically want to use nth-child(3n) on the $listObjects variable.
If the method above isn’t possible, the $listObjects variable is being populated like so…
var $listObjects = $data.find('li[data-type=' + $filterType + ']');
Would it be possible to add the nth-child(3n) to that line?
Use
filter:So this should do it:
If you don’t need
$listObjectsfor anything else then you could include the:nth-childin your originalfind:Let us clarify what’s going on a little bit. Given this HTML:
If we say
$('li[data-id]')we’ll get One, Three, Four, Five, Six, and Seven for the obvious reason.If we say
$('li[data-id]').filter(':nth-child(3n)'), we’ll get Three and Six when you’re probably expecting to get Four and Seven. What happens here? The:nth-childselector is being applied to all of the children of the<ul>rather than just those that match[data-id]. From the fine manual:So this behavior matches the spec even if it is a little confusing and the spec could be more explicit on how things interact.
If we say
$('li[data-id]:nth-child(3n)')then we get the (expected?) Four and Seven, i.e. every third element of$('li[data-id]').And finally, we can say this:
Remember that
nth-childis a CSS selector and thus 1-based, hence the(i + 1)in the test function. That will give us every third element again so we get Four and Seven. Note that$.grepgives you a plain array of DOM elements so you’ll want to wrap that array in$()if you jQuery-ified version.Demo: http://jsfiddle.net/fw4xr/
Summary:
filtermay not be what you want but adding the:nth-child(3n)to the original selector probably is. Alternatively, you could use$.grepto grab the part of the$listObjectsarray that you’re interested in. And the behavior offilteris a bit confusing.