Looking for assistance with implementing CSS on alternating rows within a table via JavaScript

My JavaScript code dynamically creates rows in an HTML table using a for loop.

Below is the for loop that generates rows for my HTML table:

for(var j=0;j<5;j++) {

     var row =  createNewRow(obj);
     jQuery("#test").append(row);

}

function createNewRow (obj)
{
    // html for creating five rows per page

    var str="";
    str+=<tr>;
    str +=<td>;
    str +=<td>;

    ......

    str +=<tr>;

    return str;
}

I have successfully created five rows per page, but I'm now looking for help with applying CSS to alternate rows in the table.

Answer №1

Check out the :nth-child() documentation

Cascading Style Sheets

table tr:nth-child(odd){
    //applies styles to odd rows
}
table tr:nth-child(even){
    //applies styles to even rows
}

Answer №2

Experiment using CSS:

table tr:nth-child(odd) td {
    //defines styles for odd rows
}
table tr:nth-child(even) td {
    //applies styles to even rows
}

Utilize jQuery:

$(document).ready(function()
{
  $("tr:even").css("background-color", "#000000");
  $("tr:odd").css("background-color", "#000000");
});

Answer №3

Give these a shot:

tr:nth-child(even)
{
  background: #CCC;
}

Alternatively

tr:nth-child(odd)
{
  background: #f00
}

Answer №4

for(let i=0;i<10;i++) {

     let row =  createNewRow(data,i);
     jQuery("#output").append(row);

}

function createNewRow (data,i)
{
    // HTML for generating ten rows per section

    let str="";
    str+=<tr>; 
    if(i%2===0){ str += "class='even'>";}
    if(i%2===1){ str += "class='odd'>";}
    str +=<td>;
    str +=<td>;

    ......

    str +=</tr>;

    return str;
}

Next, implement CSS for the classes 'odd' and 'even'

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

Problem with Background-sizing in Mobile Webkit

After applying these CSS rules, everything looks great on desktop and Firefox mobile: body{ background: url(../img/home-background.jpg) no-repeat center center fixed; -webkit-background-size: cover; background-size: cover; } However, when vie ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

"Struggling with AngularJS nth-child not functioning properly within an ng-repeat loop

I've been working on changing the styling of every second row of content displayed on the page using ng-repeat. I managed to make it work for font color, however, I'm struggling with changing the background color. Below is my code. I would appre ...

Tips for locating the highest number in JavaScript

I'm having trouble with my code where the first number, even if it's the largest, is not displaying as such. Instead, it shows the second largest number. Even when following suggestions, I encountered an issue where if the numbers are entered as ...

Despite using "border-box" for the box-sizing property, the table cells are

Padding needs to be added to the cells of a table, but this is causing overflow issues with text and inputs inside the table. Despite attempting to set box-sizing: border-box, the problem persists. An example below demonstrates the issue: * { box-siz ...

Having trouble with my Javascript code - my HTML page is refusing to load and the innerHTML

Below is my code in the HTML file. I have implemented a flatpickr date picker to allow users to select a date. On closing the calendar, I intend to update the current document by adding some HTML content. However, this functionality does not seem to be wor ...

Utilize Flexbox and Material UI to position Item at the bottom of the layout

I'm attempting to include Unassigned Text at the bottom of my Container, following the layout shown in this mockup:https://i.sstatic.net/863cl.png Here is the code I currently have. I'm facing difficulty in getting the border between the play bu ...

Tips for decreasing the file size without compromising the clarity of the image?

Currently, I am working on an image puzzle project using jQuery. Everything is almost complete, except for one issue: when the user selects the 2x2 puzzle, the cropped image size appears too large (the original cropped size). I need to reduce the size of t ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

The triggering of mouse events on 3D spheres in THREE.js does not occur accurately in the specified location

I've taken over a project from someone else and it's actually pretty cool. The goal is to create a dynamic diagram with nodes (spheres) that can be clicked on to reveal related nodes in a new diagram. Right now, I'm focusing on the clickabl ...

What is the best way to optimize Bootstrap 5 grids for mobile responsiveness?

Within my portfolio, I have a projects section that switches between having the description on the left with an image on the right and vice versa. Despite my efforts to make it responsive, I'm struggling to figure out how to ensure the image appears a ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

Leveraging template's JavaScript within a React JS environment

I'm currently working on developing an application in React JS using an HTML/CSS/JavaScript template. My main focus right now is creating a navbar for the app, which involves incorporating several scripts into the code. I've encountered an error ...

What is the reason behind jQuery appending a closing tag to the end of the text when adding a table dynamically?

$('#all_locations').append("<table>"); $('#all_locations').append("<tr><th>City</th></tr>"); $.each(data, function(i, item){ $('#all_locations').append("<tr>"); $('#all_locatio ...

What is the best way to position the 'search' box on the right side of an Angular mat table?

Utilizing mat-card, I need the add button and search box to be aligned horizontally in a single line. Specifically, I want the add button on the left side and the search box on the right side. I have crafted the following html structure, but unfortunately ...

How can I prevent dataTable resizing?

Is there a solution to prevent datatable resizing? For instance, when the default number of rows per page in the datatable is set to 10 rows. If you input 13 rows into the datatable, it will be divided into 2 pages - with 10 rows on the first page and 3 ro ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

Assigning an object to a field within an array using Vega-lite

I am currently working on an interactive data dashboard with a dataset stored in an array of objects. I want to enhance the functionality by displaying data from one object at a time instead of all objects collectively, which is already functioning well. T ...

Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event. I sent the data and $event from the parent to the child as shown below. in the parent component: <v-filter :sortTypePrice="sortTypePrice" :sort ...

Convert a document into a PDF format and then transfer it to a server for safekeeping

I am in need of a solution for saving completed web forms as PDFs, which I can then store in my database for future reference. My staff often fill out these forms for various purposes and being able to convert them into PDFs would greatly streamline our wo ...