One method is able to operate on a variety of tables

I am faced with the challenge of wrapping text in each header column of a table generated in a backend, and adding it to each body column cell using .html() and .prepend(). The expected result is that the text will appear in green.

However, the problem arises when there are two independent tables on a page. The green text in the first table displays correctly, but the header text from the first table gets added to the body column cells of the second table, causing a messy layout as shown in the image below: https://i.sstatic.net/BssZ5.jpg

The desired layout for the two tables should resemble the image below: https://i.sstatic.net/qSKmF.jpg

I am seeking guidance on how to resolve this issue. Any help would be greatly appreciated. Thanks

$(document).ready(function() {
  $("table thead tr th").each(function(i) {
    let bodyCode = $("<span>", {
      text: $(this).text()
    });
    $(`table tbody tr td:nth-child(${i+1})`).prepend(bodyCode);
  });
});
table {
  width: 100%;
  border: 1px solid gray
}

span {
  color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<table>
  <thead>
    <tr>
      <th>Day</th>
      <th>Earn</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Monday</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>Tuesday</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>
</p>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
      <td>$200</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
      <td>$180</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

Answer №1

The primary concern lies in the necessity to iterate through each table initially.

This piece of code:

  1. Retrieves every table element within the each loop.
  2. Finds the th elements in that specific table using another each loop.
  3. Extracts the desired text from the th element and encapsulates it within a <span> tag.
  4. Subsequently, it locates the current th element, identifies its parent table, and then pinpoints each td element.

$(document).ready(function() {
  // Iterate through each table
  $("table").each(function() {
    // Discover all the tds in each table
    let th = $(this).find('thead tr th');
    // Iterate through each th in the table
    th.each(function(i) {
      let bodyCode = $("<span>", {
        text: $(this).text()
      });
      // Locate the td elements in this specific table.
      $(this).parents('table').find(`tbody td:nth-child(${i+1})`).prepend(bodyCode);
    });
  });
});
table {
  width: 100%;
  border: 1px solid gray
}

span {
  color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Day</th>
      <th>Earn</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Monday</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>Tuesday</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>
<br>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
      <td>$200</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
      <td>$180</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

<p> added extra tables for proof of concept</p>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
      <td>$200</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
      <td>$180</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>
<br>
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</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

Should you create an archive - Retain outcomes or retrieve them whenever needed?

I am currently developing a project that allows users to input SQL queries with parameters. These queries will be executed at specified intervals determined by the user (e.g., every 2 hours for 6 months), and the results will be sent to their email address ...

All components in my app are being styled by CSS files

Currently, I am facing an issue with my React app in VS Code. My goal is to assign a distinct background color to each component. However, the problem arises when unwanted CSS styles from other files start affecting components even though they are not impo ...

Using the CSS selector :contains() does not function properly when there are line breaks present

<div>A very lengthy text that goes on and on</div> When rendered, A very lengthy text that goes on and on will appear as HTML removes the line breaks. However, locating the div using the :contains() CSS selector is challenging due to the lin ...

Exploring the utility of the load_file function in the simple HTML DOM method

After writing this code and it was functioning properly. <?php include ('require/simplehtmldom_1_5/simple_html_dom.php'); echo $html=file_get_html('http://www.site.com'); ?> Now I want to make it work using the object method. He ...

Having Difficulty with Splicing Arrays in React?

Currently working on learning React and trying to develop my own mini-app. I'm basing it very closely on the project showcased in this video tutorial. I've run into an issue with the comment deletion functionality in my app. Despite searching va ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

The issue of HTML form not displaying within a Java servlet environment

While following a basic tutorial to learn Java servlet programming in Eclipse, I encountered an issue with the browser not rendering the submit button in the HTML form. Despite reviewing the code multiple times, making small modifications, and even double- ...

Mix up the colors randomly

After searching extensively, I have been unable to find exactly what I am looking for. The closest matches only cover a portion of my needs which include: I am seeking a randomly selected color scheme that I have created but not yet implemented in code. T ...

MUI version 5 - Keep styling separate from component files

Seeking to segregate styling from component File in MUI v5. In the past, I accomplished this in v4 by utilizing makeStyles as shown below: Page.style.js: import { makeStyles } from "@material-ui/core"; export const useStyles = makeStyles({ ro ...

Seeking assistance with parameter passing using Ajax, specifically with deferred and promise functionality

While this may be a common issue for learners, I have yet to find a straightforward solution to the problem: The following code works without using Ajax: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> ...

What could be causing my ajax post to be cut short?

After making enhancements to my MVC service with more thorough error handling and logging, I have encountered a persistent error multiple times without being able to reproduce it. Unterminated string. Expected delimiter: ". Path 'Breadcrumbs[18].Para ...

Tips for activating hover effect on child components by hovering over the parent container?

At the moment, I am tackling an issue with CSS in a nextJS web application. The problem lies in a parent div element that contains multiple child elements. My goal is for hovering over the parent div to trigger changes on the child elements as well. Here& ...

The execution of jQuery was hindered due to the implementation of PHP include

Having an issue with jQuery not working in index.php when including the file header.php. The nav sidebar is included, but clicking the chevron does not trigger anything. It only works when I directly include header_user.php without checking the UserType in ...

The function iframe.scrollTo() is not effective for scrolling through Excel or PowerPoint documents on an iPad

I am trying to create a custom scrolling feature for iframe content specifically for iPad. Currently, I have set up my iframe like this: <div id="scroller" style="height: 300px; width: 100%; overflow: auto;"> <iframe height="100%" id="iframe" ...

Is there a way to control the text animation loop on iTyped, both starting and stopping it?

Currently utilizing React, MUI, along with iTyped The animation implemented involves backspacing text and typing the next word in a specified array until reaching the final word. I am looking to enable a click function on the div containing this animation ...

Display PHP array information in an HTML table

I am facing an issue with an array that contains a record set generated by the CodeIgniter model. When attempting to display these records in an HTML table using my view, the layout is not rendering correctly. Here is a snippet of my view: <html> & ...

Aggregate the JSON data by grouping and calculating the total value

Looking to organize a set of JSON values by grouping them based on different geographical regions. Identified,Proposal Submitted,QO under Evaluation,Negotiation & Contracting,Closed Lost,Closed Won are all grouped according to count and pipelinevalue ...

Arrange TD's from various TR's underneath each other in a stack

Imagine we have a table that needs to be made responsive. <table> <tr> <td>Dog Image</td> <td>Cat Image</td> </tr> <tr> <td>Dog Text</td> <td>Cat Text</td> & ...

Activate the capture property for the file selection based on the label that is selected

This is a form that consists of two labels: <form method="POST" action='/process' enctype="multipart/form-data"> <div> <label for="file" class="upload-button"><i class=" ...

Font size transition on pseudo elements is not functioning properly in Internet Explorer when using the "em" unit

When I hover over, the font awesome icon and text on this transition increase in size. All browsers work well with this effect except for IE 11. This example demonstrates the same transition using px (class test1) and em (class test2). While using px wor ...