How to use the first-child selector for a specific class

7

Hello, I have several divs and some of them have a 'test' class, I would like the first-child selector to highlight only the first DIV that has the 'test' class, however, it only works if the 'test' class is in the first div. From what I understand, the selector takes the first object of the type and not the class actually. Does anyone have any ideas? In this example below, I wanted the div with "Test 2" to be highlighted by the selector (it is the first DIV that has the test class).

.teste:first-child{
	background-color:#F00;
	border:solid 4px #33CCCC;	
}
<div>
  Teste 1
</div>
<div class="teste">
  Teste 2
</div>
<div class="teste">
  Teste 3
</div>
<div class="teste">
  Teste 4
</div>
    
asked by anonymous 30.12.2015 / 23:03

1 answer

6

There are no selectors that do this unfortunately, the current selectors work on the element tag and not on your class. The ideal here would be :first-of-class that does not exist.

There's an interesting idea that solves your problem. That's using the selector ~ .

In this case, you apply the style to all classes, and then undo them using the .classe ~ .classe selector, and thus delete the style in all but the first one ... The selector looks for an element with the class x, preceded on the other hand with class x.

It would look like this:

div.teste {
    background-color: #F00;
    border: solid 4px #33CCCC;
    color: #ccf;
}

.teste ~ .teste {
    background-color: transparent;
    border: none;
    color: #000;
}
<div>
  Teste 1
</div>
<div class="teste">
  Teste 2
</div>
<div class="teste">
  Teste 3
</div>
<div class="teste">
  Teste 4
</div>

jsFiddle: link

As I mentioned, there is no immediate solution with CSS, although it is executable. If you want to use JavaScript to avoid overloading CSS with rules that can be complex to remove you can use it like this:

var primeiroTeste = document.querySelector('.teste');
primeiroTeste.classList.add('classe');

where would you be in CSS:

.classe {
    background-color:#F00;
    border:solid 4px #33CCCC;   
}

jsFiddle: link

    
30.12.2015 / 23:14