5

I have the following html and I want to show only the first ".xpto" element. My problem is that I'm removing the class .xpto dynamically, so when I do it, the first .xpto element will be the second inner div. How can I accomplish this?

<div>
    <div class="xpto"></div>
    <div class="xpto"></div>
    <div class="xpto"></div>
    <div class="xpto"></div>
</div>

I tried, :first-child, :first-of-type and :nth-child(1n) but nothing worked. Any ideas? (CSS only)

Test case: http://jsfiddle.net/7YRAF/

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
BMCouto
  • 61
  • 3

2 Answers2

2

Though this is not entirely possible with CSS, this would work with the current example:

EXAMPLE HERE

div:not(.xpto) + div.xpto {
    display:block;
}

It basically just selects the succeeding .xpto element if its previous element doesn't have the class .xpto. Since you're removing the class, the 'first' element is selected. This obviously wouldn't work in all instances though, therefore you should just use jQuery for this since you're already using it.

EXAMPLE HERE

$('div > div.xpto:first').addClass('visible');

For an alternative, you could also do something like this:

EXAMPLE HERE

div > .xpto {
    display:block;
}
div > .xpto ~ .xpto {
    display:none;
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

You need to give that wrapping div a class name, then you can use the first-child pseudo selector.

<div class="wrapper">
 <div></div>
 <div></div>
 <div></div>
 <div></div>
</div>

CSS

.wrapper div:first-child {
 display:block;
}
Matt Lambert
  • 3,655
  • 2
  • 24
  • 17
  • No you can't Matt, once you remove the .xpto class from the first div, it's not :first-child anymore. Please try it. – BMCouto Mar 19 '14 at 11:25
  • Hi, the .xpto classes have no bearing on using :first-child. You are targeting the first div in the .wrapper parent. The class on the inner divs can be anything, it doesn't come into play. I updated the code to show this. Remember, you need to insert some content into the div, otherwise when you flip to display:block; nothing is going to show. I've created a fiddle that shows this at: http://jsfiddle.net/9KbB5/ – Matt Lambert Mar 19 '14 at 16:59
  • Matt your fiddle doesn't mirror my situation. If you try that approach, using my fiddle you'll see why :first-child won't do it. Also, check Josh's answer, which lead me to the solution. Thanks! – BMCouto Mar 20 '14 at 18:52