I'm looking for help with using the nth-child CSS selector. If you take a look at my HTML...
<div id="report">
<div class="a">A</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="b">B</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="b">B</div>
<div class="a">A</div>
<div class="a">A</div>
<div class="a">A</div>
</div>
...I have a row of letters like this:
AAAABAAAABAAA
I want to only show the first B and hide the others, however I cannot seem to select the classes as I expect. When I try to use:
.b:nth-child(1){
display: block;
}
.b:nth-child(n+2){
display: none;
}
It doesn't work and I have to select it using (5) to just get the first B.
Help would be greatly appreciated.
JSFiddle: http://jsfiddle.net/SrM9T/1/
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
nth-child accepts two keywords in that spot: even and odd. Those should be pretty obvious. “Even” selects even numbered elements, like the 2nd, 4th, 6th, etc. “Odd” selects odd numbered elements, like 1st, 3rd, 5th, etc.
Writing Complex :nth-child() Selectors It works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.
Pseudo-class :nth-child()The :nth-child() pseudo-class represents an element that has an+b siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.
This does not require javascript
.b ~ .b{
display:none;
}
http://jsfiddle.net/KYAj8/1/
General sibling combinator
The general sibling combinator selector is very similar to the adjacent sibling combinator selector The difference is that that the element being selected doesn't need immediately succeed the first element, but can appear anywhere after it.
More info
this is your jquery
$('.b').not('.b:eq(0)').hide();
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With