1

I have 2 separate tables, every one of the td elements can contain "selected" class, how can I select the first and last td elements with "selected" class in both tables.

<table class="table1">
    <tr>
        <td>Jill</td>
        <td class="selected">Smith</td>
    </tr>
    <tr>
        <td class="selected">Hill</td>
        <td class="selected">Morris</td>
    </tr>
</table>

<table class="table2">
    <tr>
        <td class="selected">Mills</td>
        <td>Garyn</td>
    </tr>
    <tr>
        <td>Lee</td>
        <td>Gutierrez</td>
    </tr>
</table>

The first item is the "td" with the class "selected" is Smith, and the last one is "Mills"

1 Answers1

0

Use javascript and set style to first and last with querySelectorAll

var matches = document.querySelectorAll(".selected");
if(matches.length>0){
matches[0].style.color="red";
matches[matches.length-1].style.color="red";
}
<table class="table1">
    <tr>
        <td>Jill</td>
        <td class="selected">Smith</td>
    </tr>
    <tr>
        <td class="selected">Hill</td>
        <td class="selected">Morris</td>
    </tr>
</table>

<table class="table2">
    <tr>
        <td class="selected">Mills</td>
        <td>Garyn</td>
    </tr>
    <tr>
        <td>Lee</td>
        <td>Gutierrez</td>
    </tr>
</table>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47