Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class.

I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuery). Despite trying multiple approaches, I have been unsuccessful so far, encountering either null results or error messages stating "invalid selector". The solution provided in a Stack Overflow thread here has also failed to work for me.

Here are 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 instance:

<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 this scenario, my objective is to capture the value of Value I want, but I seem unable to do so. Can anyone identify what might be going wrong?

Answer №1

CSS does not offer a "last" pseudoclass, and neither :last-child nor :last-of-type will achieve what you are looking for.

If you intend to select the element using JavaScript, it's quite simple: Identify all td elements without the class .disabled and then choose the last one:

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

You can also limit this selection to a specific table:

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

Here is an 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content. The ...

How can the selected value be shown in the dropdown menu after moving to a different webpage in HTML?

My application features 4 roles displayed in a dropdown menu. When a specific role is clicked, it should go to the corresponding href link that was specified. However, I encountered an issue where after navigating to the second HTML page, the selected rol ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

Vue 2 - Error: The function is not defined at HTMLInputElement.invoker (vue.esm.js?65d7:1810)TypeError: cloned[i].apply

I encountered the following error: Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810) I have set up my project using vue-cli (simple webpack), and below is the code for my component: <template ...

Unable to adjust table, row, and cell heights in Outlook template due to HTML/CSS formatting issues

I'm struggling to make the height of the leftmost (commented) nested table adjust automatically based on the content in the right section. It displays correctly in Chrome, but does not stretch in Word/Outlook. Any ideas on how to fix this for Word/Ou ...

What causes the behavior of Node.js to be the way it is?

Check out this code snippet function removePrototype() { var obj = {}; for (var _i = 0, _a = Object.getOwnPropertyNames(obj.__proto__); _i < _a.length; _i++) { var prop = _a[_i]; obj[prop] = undefined; } obj.__proto__ = ...

The final element that fractures all its sibling elements positioned absolutely

I am experiencing an issue with a container div that contains 5 absolutely positioned images. When I specify the last image as absolutely positioned, all other images lose their positioning and stack at the top. The container itself is relatively position ...

When I try to hover my mouse over the element for the first time, the style.cursor of 'hand' is not functioning as expected

Just delving into the world of programming, I recently attempted to change the cursor style to hand during the onmouseover event. Oddly enough, upon the initial page load, the border style changed as intended but the cursor style remained unaffected. It wa ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

Exploring the world of XD plugins, utilizing npm packages and Node.js APIs

Is it feasible to integrate npm packages and Node.js APIs into my Adobe XD plugin development process? ...

The left margin is malfunctioning

As a newcomer to css, I am struggling with adding margin-left to my paragraph and <h2>, and it's not taking effect. I have a 700px div and I want to add a 10px margin-left to both <p> and <h2> in relation to the image. Despite my e ...

What is preventing me from setting the maxwidth in Android WebView during onLayout?

I am attempting to customize the onLayout function of a WebView in order to limit the size of large images to fit within the screen size. Within my extended WebView, I have tried the following code: @Override protected void onLayout(boolean changed, i ...

Customize Your Google Maps with Checkboxes for Style Options

Trying to make dynamic changes in the style of a Google Maps using checkboxes. Some checkboxes control colors of features, while others control visibility. Having trouble figuring out how to combine different features of styles since they are not strings ...

Attempting to replicate the action of pressing a button using Greasemonkey

I am currently working on a greasemonkey script to automate inventory updates for a group of items directly in the browser. I have successfully implemented autofill for the necessary forms, but I am facing challenges with simulating a click on the submissi ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

Conflicts in routing between Node.js and AngularJS

Currently, my setup involves NodeJS, gulp, and Angular with ui-router. However, I have encountered an issue when configuring Angular to remove the tag (#) from the routes. The problem arises as Angular's routes do not seem to work properly, and the na ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...