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

3

I want to add background to the row of a table where one of its columns is: Value 1 . I tried using pseudo-class contains and innerHTML but all to no avail.

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 can 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?
asked by anonymous 27.03.2017 / 18:49

2 answers

2

From the selectors I see in documentation , you can not do that. But you can select via attributes and attribute values, so if you put text in an attribute it is possible to do so.

I did it on the JSFiddle for you to see.

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

    
27.03.2017 / 19:02
2

Complement the @Artur with CSS only you can not do this, according to documentation . An alternative is to use Jquery , which can be done like this:

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

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

There is a very conceptual basis for explaining why this was not implemented. It's a combination of basically 3 aspects:

  • The textual content of an element is effectively the child of that element. element
  • Unable to target text content directly
  • CSS does not allow ascending with selectors
  • These 3 together mean that by the time you have text content you can not climb back to the parent element, and you can not 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 route solutions or the like that would greatly complicate the application of CSS to DOM .

        
    27.03.2017 / 20:11