Applying a CSS class to a newly generated row with JavaScript

I have a JSP page where I dynamically add rows to a table using a different Javascript function than in my previous query. While I can add elements to the table columns, I'm unable to apply a style class that is defined in a CSS file.

Here is my Javascript function:

function addRow(tableID) {
    try{
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount-1);

        var i=0;
        var newCell = row.insertCell(i);
        newCell.innerHTML ='<h4>Type &nbsp;&nbsp;&nbsp;</h4>';

        i++;
        newCell = row.insertCell(i);
        newCell.innerHTML ='<input type="text" name="type7" id="type8" size="30"/>';
        i++;
        newCell = row.insertCell(i);
        newCell.innerHTML ='';
        i++;
        newCell = row.insertCell(i);
        newCell.innerHTML ='<h4>Description &nbsp;&nbsp;&nbsp;</h4>';
        i++;
        newCell = row.insertCell(i);
        newCell.innerHTML ='<textarea name="textarea2" id="textarea2" cols="28" rows="2"></textarea>';

    } catch(e) {
        alert(e);
    }
}

Here is my HTML snippet:

<table id="table1" width="792" border="0">

<tr class="rowdiv">
      <td class="formlabel"><h4>Type &nbsp;&nbsp;&nbsp;</h4></td>
      <td class="formfield"><input type="text" name="type7" id="type8" size="30"/></td>
      <td class="formgap"></td>
      <td class="formlabel"><h4>Description &nbsp;&nbsp;&nbsp;</h4></td>
      <td class="formfield"><textarea name="textarea2" id="textarea2" cols="28" rows="2"></textarea></td>
      </tr>

      <tr class="rowdiv">
        <td width="170" class="formlabel">&nbsp;</td>
        <td class="formfield">&nbsp;</td>
        <td class="formgap"></td>
        <td class="formlabel">&nbsp;</td>
        <td class="formfield"><h6 onclick="addRow('table1')">Add policy</h6></td>
      </tr>

    </table>

I want to apply the same styles (classes formlabel, formfield, and formgap) to newly created rows as well.

I tried searching on Google but found codes that extract style attributes one by one and copy them to a new row, whereas I want to include the class names directly.

Here is my CSS section:

.formlabel{                         
    text-align: right;
    font: Verdana, Geneva, sans-serif; 
    font-weight: lighter;
    margin: 0px;
    padding: 0px;
    text-transform: capitalize;
    color: #000000;
}

/* More CSS rules here */

.formfield input {text-transform: capitalize; font:Verdana, Geneva, sans-serif;}

.formlabel h5{margin: 0px; padding: 0px; font-weight: lighter;}
.formfield h6{margin: 0px; padding: 0px; font-weight: lighter;}

Answer №1

You can store the element's classes in the classList property and add a new class by using the add method, like this:

newCell.classList.add('yourNewClass');

Answer №2

const targetTable = document.getElementById(tableID);
const numRows = targetTable.rows.length;
const newRow = targetTable.insertRow(numRows - 1);
newRow.className = "row-style";

let index = 0;
let newCell = newRow.insertCell(index);
newCell.innerHTML ='<h4>Type & & </h4>';
newCell.className = "label-form";

index++;
newCell = newRow.insertCell(index);
newCell.innerHTML ='<input type="text" name="type7" id="type8" size="30"/>';
newCell.className = "input-field";

index++;
newCell = newRow.insertCell(index);
newCell.innerHTML ='';
newCell.className = "form-space";

index++;
newCell = newRow.insertCell(index);
newCell.innerHTML ='<h4>Description & & </h4>';
newCell.className = "label-form";

index++;
newCell = newRow.insertCell(index);
newCell.innerHTML ='<textarea name="textarea2" id="textarea2" cols="28" rows="2"></textarea>';
newCell.className = "input-field";

Answer №3

let cellInsert = row.insertCell(i);
cellInsert.innerHTML ='<h4>Category &nbsp;&nbsp;&nbsp;</h4>';
cellInsert.className = 'formlabel';
i++;
cellInsert = row.insertCell(i);
cellInsert.innerHTML ='<input type="text" name="category7" id="category8" size="30"/>';
cellInsert.className = 'formfield';
i++;
cellInsert = row.insertCell(i);
cellInsert.innerHTML ='';
cellInsert.className = 'formgap';
i++;
cellInsert = row.insertCell(i);
cellInsert.innerHTML ='<h4>Details &nbsp;&nbsp;&nbsp;</h4>';
cellInsert.className = 'formlabel';
i++;
cellInsert = row.insertCell(i);
cellInsert.innerHTML ='<textarea name="description2" id="description2" cols="28" rows="2"></textarea>';
cellInsert.className = 'formfield';

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

Footer rises with bootstrap zooming

Hey everyone! I'm a beginner in the world of web development and currently working on creating my own website. I've run into an issue with my footer - I want it to stay fixed at the bottom even when zoomed in, but for some reason, when I zoom in, ...

React JS Issue: Real-time Clock not updating in React component

I have a react application designed for attendance tracking. The issue at hand is that the time displayed does not update in real-time. Once the app is initially rendered, the time remains static. (It only updates when the app is reloaded) The code snipp ...

Concealing a Specific Element with Text using jQuery

Is there a way to conceal the section that includes the element labeled as "Product Tags" on a webpage? ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

The while loop is unyielding, persisting beyond the realm of

After executing this script, it displays the HP values for both Pokemon. Pressing 1 and pressing enter subtracts your attack points from the enemy's hit points. The goal is to stop the battle when either you or the enemy reaches 0 or below hit points ...

The submit button is not reading the JavaScript file for validation and instead goes directly to my PHP file

**Hello, I'm new to Stack Overflow. My submit button is not reading the JavaScript file I created; instead, it goes straight to the PHP file without validating the input fields first in the JavaScript file. I've been stuck here for hours and can& ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Unwanted transparency issue in MaterialUI (MUI) BottomNavigation

Greetings fellow hobby developer! I recently embarked on a project using create-react-app and incorporated MUI dependencies. One feature I added was a fixed BottomNavigation, which you can view in action here. Interestingly, in CodeSandbox, the BottomNavi ...

Which is more effective: using the try-catch pattern or the error-first approach

My main focus is on node.js and express.js, although I am relatively new to JavaScript overall. When it comes to error handling, the official recommendation is to use the try-catch pattern. However, some developers argue in favor of sticking with the tradi ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

What is the best way to resize an image in HTML based on a percentage of its height?

Within my HTML code, I have a PNG image that has been adjusted in size using CSS: .adjust-image { border:1px solid #021a40; display: block; width: auto; max-width: 100%; max-height: 1000px; } .img-container { position: relative; } ...

Enhancing the efficiency of a JavaScript smooth scrolling feature for numerous listed items

I have been experimenting with recreating the recent Apple Mac retrospective using only CSS and JavaScript to create a small timeline of projects. While I have successfully implemented the layout for the full-screen hero and the expand-on-hover effect, I a ...

What is the best way to design a new class that will serve as the parent class for both of my existing classes, allowing them

I am facing a challenge with my programming classes. I have two classes, "Player" and "Enemy", each with similar methods and properties. I want them to inherit from a parent class that I'll create called "Game Object". How can I approach creating thi ...

"Encountered an error while trying to define a Boolean variable due

I am in the process of creating a TF2 trading bot with price checking capabilities. I encounter an issue while trying to define a boolean variable to determine if the item is priced in keys or not. My attempt at replacing isKeys with data[baseName].prices ...

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

Can the functions passed into Material-UI withStyles() be relocated within the component?

Attempting to break down the components of my dashboard into smaller parts has proven challenging due to their dependence on drawerWidth. Initially, I considered moving drawerWidth into the state so it can be passed down to each component. However, I encou ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

What is the best way to cut out a portion of a div using CSS?

I have a scaled down version of my project, but it's not quite what I need. I would like the green div to have some transparency so that the content behind both divs is visible (there is none in the example, but there is in my actual project). However ...