Is there a css selector that selects elements through your text?

Asked

Viewed 735 times

3

I want to add background the row of a table in which one of the columns is: Value 1. I tried with the pseudo-class contains and by innerHTML, but all without success.

Code:

table tr td [innerHTML="Valor 1"]{
  background: red;
}

table tr td: contains('Valor 1'){
  background: red;
}
<table>
    <tr>
        <td>Valor 1</td>
    </tr>
    <tr>
        <td>Valor 2</td>
    </tr>
    <tr>
        <td>Valor 3</td>
    </tr>
</table>

  • How could I use a CSS selector to select the line by column text?
  • In a more general way, how could you select a element by its content?

2 answers

2

Complement the @Artur only with CSS it is not possible to do this, according to the documentation. An alternative is to use Jquery, that can be done so:

$("table tr td").filter(function (){
  return $(this).text() == "Valor 1";
}).css("background", "red");

In one of the answers of this question, says the following:

There is a very conceptual basis to explain why this has not been implemented. It is a combination of basically 3 aspects:

  1. The textual content of an element is effectively the child of that element
  2. Cannot segment text content directly
  3. CSS does not allow ascent with selectors

These 3 together mean that by the time you have text content you can’t climb back into the parent element, and you can’t style the current text. This is probably significant, since descending only allows a unique accompaniment of the context. Ascending or other selectors involving other axes introduce the need for more complex path or similar solutions that would greatly complicate the application of CSS at the GIFT.

2


By the selectors I see on documentation, cannot do this. But you can select via attributes and attribute values, so if you put the text in an attribute it is possible yes.

I did in the Jsfiddle for you to see.

div[atributo_texto="teste"]{
  background-color:red;
}
<div id="divTeste" atributo_texto="teste">
teste
</div>

<div id="divTeste2" atributo_texto="batata">
batata
</div>

The closest content selector I see in the documentation is :empty, that selects empty elements

  • I saw that answer a little later, thanks :)

Browser other questions tagged

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