Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the first-child with a given class, how? [duplicate]

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/

like image 212
BMCouto Avatar asked Nov 02 '22 03:11

BMCouto


1 Answers

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;
}
like image 182
Josh Crozier Avatar answered Nov 08 '22 03:11

Josh Crozier