Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS selector that only selects the first cell of each row with specific class name

How to write CSS selector that given this table

<table>
  <tr>
    <td>Cell 1</td>
    <td class="target">Cell 2</td>
    <td class="target">Cell 3</td>
    <td>Cell 4</td>
  </tr>
  <tr>
    <td class="target">Cell 5</td>
    <td>Cell 6</td>
    <td>Cell 7</td>
    <td class="target">Cell 8</td>
  </tr>
</table>

selects only "Cell 2" and "Cell 5"? The order of which cell might have the class name is random for each row. The only guarantee is each row must have at least one cell with the class.

I’ve tried something like td.target:first-of-type, but selectors like this apply the pseduo class first then restrict on the class name, resulting "Cell 5". I need to apply the class name first, while maintaining its n-th child state, then apply the :first-of-type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this possible?

>Solution :

You can target all the .target elements, that are not a .target following a .target 🙂

.target:not(.target ~ .target) { color: red }
<table>
  <tr>
    <td>Cell 1</td>
    <td class="target">Cell 2</td>
    <td class="target">Cell 3</td>
    <td>Cell 4</td>
  </tr>
  <tr>
    <td class="target">Cell 5</td>
    <td>Cell 6</td>
    <td>Cell 7</td>
    <td class="target">Cell 8</td>
  </tr>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading