Take part of the CSS class name

Asked

Viewed 224 times

3

Is there any way to get "part of the class name" in CSS?

I say this because of the example:

<div class="result_itens_id1255454">

Let’s assume that this id1255454 is random, so there would be no way I could stylize this div specifically because it will always change (and I have no control over the backend that builds this structure)

It would take part of the name of this class?

For example, div.result_itens_ so I can style the element?

2 answers

4


You can even use the selector ^= of the CSS that will apply the style based on the prefix of the value in that attribute. For example, [class^="result_itens_"] will apply the style to all elements that the class starts with the value result_itens_.

[class^="result_itens_"] {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="result_itens_id1255454">

</div>

The problem is when the element has this class, but is not the first in the element.

[class^="result_itens_"] {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="foo result_itens_id1255454">
 Não ficarei vermelho
</div>

For now class begins with foo, no longer with result_itens_. There’s also the dial *= that is contains a value.

[class*="result_itens_"] {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="foo result_itens_id1255454">
 
</div>

<hr>

<div class="my_result_itens_bla">
 Por que fiquei vermelho?
</div>

That circumvents the problem of not being the first class in the element, but that allows generating false positives, as it will apply the style in all the elements that have, anyway, the value result_itens_ in the attribute class.

  • 1

    One way - not very pretty, but to do what - is to use [class*=" result_itens_"], [class^="result_itens_"] (with a space before result in the case of *=), thus greatly decreases false positives (I do not know if eliminates 100%)

  • @hkotsubo If the value after the prefix does not matter I believe that would remove all false positives even.

1

Yes, just you use:

[class^="result_itens_"]{
   propriedades aqui
}

The selector ^= will take all elements that have the class started with result_itens_. The sign ^ means beginning.

It will work in all cases where the element has only that class, or, if there is a possibility of having another (or other) class, that class is the first on the list.

  • @Andersoncarloswoss It would be class inciada same, because if it has class="result_itens_123 foo" will apply.

  • @Andersoncarloswoss That’s what I said in the answer: "class started with result_itens_".

  • @Andersoncarloswoss Oh, I understood what you meant. I changed the word "a class" to "the class" to avoid giving this problem of interpretation. : D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.