Avoiding JavaScript with CSS Attributes Selector

I am trying to hide the subsequent tr with role = "metadata" and the same data group identifier as the first tr that it encounters.

I can't use JavaScript here, and I'm trying to achieve this using pure CSS.

<table> <tbody> <!-- BEGIN this tr should be visible --> <tr data-group-id="1" role="metadata"> <td> First rows group title </td> </tr> <!-- END this tr should be visible --> <tr data-group-id="1" role="data"> <td> Row belonging to group 1 </td> </tr> <!-- BEGIN this tr should be hidden --> <tr data-group-id="1" role="metadata"> <td> Rows group title </td> </tr> <!-- END this tr should be hidden --> <tr data-group-id="1" role="data"> <td> Another row belonging to group 1 </td> </tr> <!-- BEGIN this tr should be visible --> <tr data-group-id="2" role="metadata"> <td> Second rows group title </td> </tr> <!-- END this tr should be visible --> <tr data-group-id="2" role="data"> <td> Row belonging to group 2 </td> </tr> </tbody> </table> 

Selectors like this ...

 [data-group-id="1"][role~="metadata"] ~ [data-group-id="1"][role~="metadata"] display: none 

... work very well, except that the data group identifier can change dynamically.

Something like this would be great (I know that this is incorrect CSS code, its just my fantasy with regular expressions to help illustrate the problem):

 [data-group-id="(.*?)"][role~="metadata"] ~ [data-group-id="\\1"][role~="metadata"] 

Is there a way to achieve this using only CSS?

Thanks in advance.

+4
source share
1 answer

It seems to me that using data-group-id in CSS is not practical, especially since it is dynamically changed and the conditions for owning the element are hidden or not changed. You get a huge piece of CSS that is impossible to maintain.

In the initial rendering, it would be better to add className so that you determine how server- className initial state will be shown.

 <tr data-group-id="1" role="data" class="hidden"> <td>Another row belonging to group 1</td> </tr> 

I assume that JavaScript is used to dynamically change data-group-id , so why not use JavaScript to add / remove className β€œhidden” className when / where it makes sense. At least in JavaScript you can use regular expressions;)

When you get to the point where you need to write an impossible, long, error-dependent and unreachable CSS expression, you are doing something wrong.

You will need to write some code to achieve this anyway, it can also do it in a clean way, and not try to teach it a style language that is not suitable for this work.

+3
source

Source: https://habr.com/ru/post/1380731/


All Articles