Search code examples
htmlcsselementsiblings

How to select siblings between 2 tags of same class using CSS


I have a bunch of table rows <tr></tr>

Few of which are of class = "node"

Only one of the tr.node will be of class = "active"

<tr class="node">...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr class="node">...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr class="node active">...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr class="node">...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr class="node">...</tr>

I want to select all the <tr>'s from tr.node.active to next tr.node excluding the tr.node's themselves.

This question uses jquery How to select all content between two tags in jQuery

Is there any way of doing this using CSS only, as using javascript would be difficult in the given scenario of my project?

enter image description here


Solution

  • You need to use CSS3 ~ to selecting all sibling of element.

    tr.node.active ~ tr {
        color: red;
    }
    
    tr.node.active ~ tr.node,
    tr.node.active ~ tr.node ~ tr {
        color: black;
    }
    <table>
        <tr class="node"><td>node</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr class="node active"><td>node active</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr class="node"><td>node</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr><td>tr</td></tr>
        <tr class="node"><td>node</td></tr>
    </table>