Using ES6 and Typescript, when a button is clicked, apply a class to all TD elements within the button except for the first one. No need for jQuery

A sample table structure is shown below:

<table>
    <tr>
        <td>1</td>
        <td>joe</td>
        <td>brown</td>
        <td><button onclick="addClasses()">Add Class to add TD's in this TR except the first one</button></td>
    </tr>
    <tr>
        <td>2</td>
        <td>bob</td>
        <td>blue</td>
        <td><button onclick="addClasses()">Add Class to add TD's in this row except the first one</button></td>
    </tr>
</table>

Each row in the table contains a TD element along with a button.

On clicking the button within a row, I want to apply a class to all TD elements in that row excluding the first one.

What would be the best approach to achieve this functionality?

Answer №1

When you click on the button within a row, every TD should receive a class except for the first one.

To achieve this, update the onClick bindings in your current code to preserve the context of the button being clicked. It is recommended to bind the events using addEventListener("click", addClasses);

The function addClasses can utilize the current context to navigate back to the parent of the td node and access the firstElementChild, skip it, and then iterate through the remaining children to apply the necessary class using classList.add

If classList is not supported across all versions or element types in Internet Explorer, you can utilize element.className as an alternative

function addClasses() {
  var node = this.parentNode.parentNode.firstElementChild || this.parentNode.parentNode.firstChild;
  
  // Ensure first Child Selected is an element
  while(node && node.nodeType !== Node.ELEMENT_NODE){
      node = node.nextElementSibling || node.nextSibling;
  }
  
  //skip first element child
  node = node.nextElementSibling || node.nextSibling;

  // loop through all children adding a class
  while (node && node.nodeType === Node.ELEMENT_NODE && node !== this) {
    if(node.classList && node.classList.add){
      node.classList.add("highlight");
    } else {
      node.className += " highlight"
    }
   
    node = node.nextElementSibling || node.nextSibling;
  }
}
.highlight {
  background-color: yellow;
}
<table>
  <tr>
    <td>1</td>
    <td>joe</td>
    <td>brown</td>
    <td><button onclick="addClasses.call(this)">Add Class to add TD's in this TR except the first one</button></td>
  </tr>
  <tr>
    <td>2</td>
    <td>bob</td>
    <td>blue</td>
    <td><button onclick="addClasses.call(this)">Add Class to add TD's in this row except the first one</button></td>
  </tr>
</table>

Regarding firstElementChild || firstChild in the provided code snippet:

firstElementChild may not be available in all versions and element types in IE. In such cases, you should use firstChild instead. However, keep in mind that firstChild doesn't solely select the first element node but also any #text or #comment nodes, etc.

To ensure proper skipping of the first td element, consider looping through the nodes starting from the firstChild (which could be a non-element like #Text) and checking the nodeType to exclude non-element nodes before reaching the actual element.

Answer №2

Why not simplify by adding a single class to the table element instead of adding a class to all but the first td in every tr?

HTML

<table id="table">
  ...

JS

function addClasses() {
  document.getElementById('table').classList.add('styles');
}

CSS

.styles tr td:not(:first-child) {
  // your styles here
}

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

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Discover the power of the "Load More" feature with Ajax Button on

After browsing through the previous questions and experimenting with various techniques, I've come close to a solution but still can't get it to work. The closest example I found is on Stack Overflow: How to implement pagination on a custom WP_Qu ...

How can you define a function type for a rest parameter in Typescript?

At this point, I have a function that takes in two parameters: param 'a' as a string and 'b' as a function that returns a string. My intention is to call it using a rest parameter and specify the types accordingly. However, on line 10 ...

Toggle the div's visibility to fade in and out once more

Apologies if this is a simple issue to resolve. My goal is to create a div that, when selected, will be replaced by another div with the option to switch back to the original div when "back" is clicked. This is my current progress: $(document).ready( ...

Navigating through various versions of admin-on-rest can be perplexing

This question is likely directed towards maintainers. Currently, I am using the stable version of admin-on-rest (https://www.npmjs.com/package/admin-on-rest) which is at 1.3.4. It seems that the main project repository is only receiving bug fixes, while ...

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

retrieve the value of a text form using jQuery and its corresponding id

I need help with a basic HTML form that includes jQuery. My goal is to: 1) Retrieve the value into a JavaScript variable. 2) Send it as JSON to a server. Here is the form: <div data-role="main" class="ui-content"> <data=role "form" ...

Encountering the error `RollupError: Expression expected` during the compilation of an NPM package

Following the setup of my environment to create my initial NPM package for React JS with ROLLUP bundler, I encountered a RollupError: Expression expected error message as displayed below: Error Message > rollup -c --environment NODE_ENV:development dev ...

Developing dynamic forms within arrays using AngularJS

Hey there! I've got a scenario where I have an array of people in my dynamic application. Each person, such as James, Bob, and Walter, has their own set of data that needs to be filled out using simple directives. $scope.users = [ { name: ...

Checking for the status of a checked box when the ::after pseudo-element is added after the box is marked

I need help verifying if a checkbox is checked in my selenium code. After the checkbox is checked, it adds ::after but I'm struggling to confirm the existence of that pseudo element. Can anyone assist me in resolving this issue? I have been unable to ...

Looking for advice on utilizing Node.js and MongoDB to identify platform modifications on a website

I need guidance for a project I'm currently working on. The project involves extracting headers, like the example below in Mongo document format: { "url": "google.com", "statusCode": 301, "headers": { "location": "http://www.goog ...

Border Effect Resembling Windows Tiles

When you hover your mouse over a tile in Windows, a cool effect happens: Hovering outside the tile, but within the container area: https://i.sstatic.net/yZk9f.png Hovering inside a tile: https://i.sstatic.net/LoSmk.png Hovering outside a tile at its m ...

Remove the content located beside an input element

Seeking assistance for a straightforward query: Snippet of code: <span> <input id="elemento_20_1" name="elemento_20_1" class="elemento text" size="2" maxlength="2" value="" type="text"> / <label for="elemento_20_1">DD</label> < ...

Is there a way for me to retrieve the values of <td name="pname"> when the Edit button is

When the button is clicked, I use jQuery to add items in a td that I have created. $("#ddproduct").click(function () { $('#prodcuttable tr:last').after('<tr><td name="pname">' + prodName + '</td> <t ...

Sending an array to a component in Angular without the need for a controller

How can I pass an array to a component in Angular 1 without being inside a controller (using a component-only approach)? Currently, my starting point is: <user-list users="users"></user-list> The 'users' variable is a JavaScript arr ...

What is the best method for showcasing information within an Angular Material table?

When using Angular material to display a list, I am facing an issue where the content of the list is not being displayed but the header is. Component: export class CompaniesComponent implements OnInit { displayedColumns: string[] = ['id']; ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...