Piet
Piet

Reputation: 2208

CSS/JS selector - Select last element where class is not equal to

I am trying to get from a HTML table the latest td tag from the latest tr where the latest td-tag should not have the class disabled.

Im doing this in pure JavaScript using CSS selectors (no jQuery please!). I tried a few possibilities but all returning null or "invalid selector" message. Also the solution posted in here is not working for me.

Some of my attempts:

var table = document.getElementById('example');
var test1 = table.querySelector('tr:last-child > td:nth-last-child(:not(.disabled))');
var test2 = table.querySelector('tr:last-child > td:nth-last-child:not(.disabled)');
var test3 = table.querySelector('tr:last-child > td:nth-last-child(1 of :not(.disabled))');
var test4 = table.querySelector('tr:last-child > td:not(.disabled):last-child');

For example:

<table id="example">
    <tr>
        <td> ... </td>
        <td class="disabled"> ... </td>
        <td> ... </td>
    </tr>
    <tr>
        <td class="disabled"> ... </td>
        <td> ... </td>
        <td> ... </td>
    </tr>
    <tr>
        <td> ... </td>
        <td> Value I want </td>
        <td class="disabled"> ... </td>
    </tr>
</table>

In here I need the value Value I want, but I'm not able to get it. Does someone knows whats wrong?

Upvotes: 1

Views: 1014

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

CSS doesn't have a "last" pseudoclass, and :last-child and :last-of-type are not applicable to what you want.

Since you seem to want to select the element with JavaScript, though, it's simple: Select all td that don't have .disabled and take the last one:

var list = document.querySelectorAll("td:not(.disabled)");
var last = list[list.length - 1];

Or scoped to that table:

var list = document.querySelectorAll("#example td:not(.disabled)");
var last = list[list.length - 1];

Example:

var list = document.querySelectorAll("#example td:not(.disabled)");
var last = list[list.length - 1];
console.log(last.innerHTML);
<table id="example">
    <tr>
        <td> ... </td>
        <td class="disabled"> ... </td>
        <td> ... </td>
    </tr>
    <tr>
        <td class="disabled"> ... </td>
        <td> ... </td>
        <td> ... </td>
    </tr>
    <tr>
        <td> ... </td>
        <td> Value I want </td>
        <td class="disabled"> ... </td>
    </tr>
</table>

Upvotes: 3

Related Questions