How to select the final td element in every row using JQuery or JavaScript, excluding those with a specific class

I am looking for a solution with my HTML table structure:

<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td class="treegrid-hide-column">3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>5</td>
            <td class="treegrid-hide-column">6</td>
        </tr>
        <tr>
            <td>7</td>
            <td>8</td>
            <td class="treegrid-hide-column">9</td>
        </tr>
    </tbody>
</table>

My goal is to target the last element in each row that does not have the "treegrid-hide-column" class.

Is there a way to achieve this using CSS or JS?

My current approach seems to have some issues. Here's the code snippet I've tried:

function addRightBorderOnTreetable() {
    var arr = $('.treegridCustom tbody tr td:last-child');
    for (var i=0; i<arr.length; i++) {
        var currentEl = arr[i];
        if ( !$(currentEl).hasClass("treegrid-hide-column") ) {
            $(currentEl).css('border-right', '1px solid #bfbfbf');
        }
    }
}

Answer №1

Unfortunately, CSS does not include a feature to achieve this effect directly. However, with the help of jQuery, it can be accomplished in the following way:

$("tr").each(function() {
  $(this).find("td:not(.treegrid-hide-column):last").each(function() {
    $(this).css('border-right', '1px solid #bfbfbf');
  });
});

$("tr").each(function() {
  $(this).find("td:not(.treegrid-hide-column):last").each(function() {
    $(this).css('border-right', '1px solid #bfbfbf');
  });
});
<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td class="treegrid-hide-column">3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>5</td>
            <td class="treegrid-hide-column">6</td>
        </tr>
        <tr>
            <td>7</td>
            <td>8</td>
            <td class="treegrid-hide-column">9</td>
        </tr>
    </tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The necessity to go row-by-row arises because there isn't a CSS selector for targeting the "last element not matching a specific class". In addition, jQuery's :last pseudo-class operates on the entire set of elements rather than each individual level of the selector.

Answer №2

Have you considered adding a custom class to your preferred td element?

<table>
<tbody>
    <tr>
        <td>1</td>
        <td class="right-border">2</td>
        <td class="treegrid-hide-column">3</td>
    </tr>
    <tr>
        <td>4</td>
        <td class="right-border">5</td>
        <td class="treegrid-hide-column">6</td>
    </tr>
    <tr>
        <td>7</td>
        <td class="right-border">8</td>
        <td class="treegrid-hide-column">9</td>
    </tr>
</tbody>

You can also adjust the CSS for styling effects:

.right-border {
      border-right: 1px solid #bfbfbf;
}

Alternatively, utilize a JavaScript function for dynamic changes:

function addRightBorderOnTreetable() {
    var el = $('.treegridCustom tbody tr .right-border');
    el.css('border-right', '1px solid #bfbfbf');
}

Answer №3

To achieve the desired outcome, consider implementing a for loop as shown below:

$(document).ready(function() {
addRightBorderOnTreetable();
});

function addRightBorderOnTreetable() {
   
    $.each($('tr'),function(){
        var arr2 = $(this).find('td');
         
        var j = arr2.length;
        for(j=arr2.length; j>-1;j--){
        var currentEl = arr2[j - 1];
          if (!$(currentEl).hasClass("treegrid-hide-column") ) {
            $(currentEl).css('border-right', '1px solid #bfbfbf');
            return;
          }
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td class="treegrid-hide-column">3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>5</td>
            <td class="treegrid-hide-column">6</td>
        </tr>
        <tr>
            <td>7</td>
            <td>8</td>
            <td class="treegrid-hide-column">9</td>
        </tr>
    </tbody>
</table>

Answer №4

A great technique to try is utilizing the nth-last-child() selector, you can learn more about it here

<script>
    $(document).ready(function(){
       $( 'table tbody tr td:nth-last-child(2)').css('border-right', '1px solid #bfbfbf'); 
    });
</script>

For a hands-on example, check out this Jsfiddle

Answer №5

   When styling a table, apply a border to the right side of the last child td element only if it does not have the class 'treegrid-hide-column'.
    

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

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Is there anyone who can provide a straightforward solution (code) for < something basic?

I have learned a lot about programming, but I'm stuck on one thing. How can I make an image stay in place when clicked on? What I mean is that when you click and hold on the image, then move the cursor, the image moves with the cursor. What I want is ...

Tips on how to conditionally render a button based on the presence of a link from a separate file in React

I've been working on my personal portfolio site using React and Tailwind. One challenge I'm facing is how to display the "GitHub" button for each project card only when a GitHub link is provided in my data.js file. Currently, I'm utilizing ...

Reversing the sequence of code in JavaScript - react native

I'm currently working on tracking the number of times a button is pressed within one second. For the most part, it's functioning correctly as it tracks and displays the count. The issue arises when it displays the button press count from the pr ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

The css property of *ngContainerOutlet is ineffective when applied to an ng-component with encapsulation

When I utilize *ngContainerOutlet to dynamically insert components, it wraps the component's template within an ng-component tag which causes my CSS styles to become ineffective. For example: <div class="my-class"> <ng-container *ngComp ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

Why isn't the pipe working when trying to extract the last 2 characters using

I am currently working on creating a regex pattern to extract the variables passed to a JavaScript constructor. The format of the input data will always be similar to this: app.use(express.static('public')); The regex I have devised to remove ...

Running dynamically imported jQuery script

I am in the process of developing a website that loads pages dynamically using the .load function. Essentially, I have an index.php file with a link that, when clicked, loads another page containing HTML and some jQuery code (plugins initialization and so ...

What is the process of retrieving data in PHP from $.post and storing it in a $variable?

After searching extensively, I have yet to find a solution that works for my specific issue of form posting using $.post to a php file to save data into a csv file. The formData is serialized in a separate function and stored in a constant for local stora ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Create several slider instances using a WordPress plugin

I have recently customized the Smooth Div Scroll jQuery plugin () and successfully integrated it into a WordPress website as a plugin. I have also created an options page in the WordPress admin area, allowing users to customize the slider according to thei ...

Navigating through an array of objects with Node.js

Recently, I integrated the ChartJS library into my Node web app to visualize data. The following is nested in a script tag on an EJS template page: <script> let playerStatChart = new Chart(myChart, { type: 'bar', data: { la ...

Enhancing the appearance of your website by incorporating external stylesheets and utilizing multiple class names through

Is it possible to use external CSS frameworks like Bootstrap, Semantic UI, or Foundation and still generate base64 class names? This could be achieved if there was a way to apply multiple class names. Currently, you can only assign one class name like thi ...

Has anyone created a modified version of jRails that is compatible with Rails 2.3 and jQuery 1.4?

We are revamping a website with Rails, and the current site heavily relies on jQuery v1.4 in its templates. We want to ensure that the existing scripts continue to function while also utilizing Rails' javascript helpers for our new scripts. While jRai ...

Is it necessary to always provide a return value from a redux middleware function?

After reviewing the various examples provided in the redux documentation, it seems like there is always a return value from the middlewares. However, in my experience, simply calling next(action) and not returning anything seems to work without any issues. ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

Is there a way to incorporate a deletion feature within a list of items using JavaScript?

When adding a new item, I want to include a delete button next to it so I can easily remove the item by clicking on the button. However, I am having trouble figuring out how to implement this functionality using JavaScript. You can view my code snippet he ...