The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the headers are not displaying correctly.

Does anyone know what could be causing this problem and how I can go about fixing it?

Here's the HTML code in question:

<table class="test">
                        <thead>
                            <tr>
                                <th>Bla</th>
                                <th>Bla</th>
                                <th>Bla</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Bla</td>
                                <td>Blabla</td>
                                <td>Blablabla</td>
                            </tr>
                        </tbody>                
                    </table>

<table class="test">
                            <thead>
                                <tr>
                                    <th>Not</th>
                                    <th>Not</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Twatwa</td>
                                    <td>Twatwa</td>
                                </tr>
                            </tbody>                
                        </table>

http://codepen.io/anon/pen/QbJqVv

Edit: Despite attempting the solution provided in another answer, the issue still persists. The second table now shows table headers, but they are incorrect as it just duplicates the headers from the first table.

Answer №1

As mentioned previously, it is important to handle each table individually in order to avoid confusion. Using .querySelectorAll('.test th') will grab all the th elements without considering which table they belong to.

To better illustrate this concept, here is a straightforward example of how you can approach this situation:

// Loop through each .test element
[].forEach.call(document.querySelectorAll('.test'), function (table) {
  // Retrieve header contents
  var headers = [].map.call(table.querySelectorAll('th'), function (header) {
    return header.textContent.replace(/\r?\n|\r/, '');
  });

  // Iterate through each row in tbody
  [].forEach.call(table.querySelectorAll('tbody tr'), function (row) {
    // Handle each cell within the row
    [].forEach.call(row.cells, function (cell, headerIndex) {
      // Set the appropriate attribute
      cell.setAttribute('data-th', headers[headerIndex]);
    });
  });
});

Check out the demo for a visual representation: http://codepen.io/anon/pen/NqEXqe

Answer №2

Initially, it's important to note that your HTML code is invalid as you have omitted closing tags for elements like

<tr><td></td></tr>
. It is recommended to adhere to proper HTML standards.

Furthermore, the usage of querySelectorAll is missing when targeting table bodies, resulting in only setting attributes for the first one located.

The revised snippet below addresses these issues and should accomplish your intended functionality.

var headertext = [],
headers = document.querySelectorAll(".test th"),
tablerows = document.querySelectorAll(".test th"),
tablebody = document.querySelectorAll(".test tbody");

for(var i = 0; i < headers.length; i++) {
  var current = headers[i];
  headertext.push(current.textContent.replace(/\r?\n|\r/,""));
} 

for (var tb = 0; tb < tablebody.length; tb++) {
  for (var i = 0, row; row = tablebody[tb].rows[i]; i++) {
    for (var j = 0, col; col = row.cells[j]; j++) {
      col.setAttribute("data-th", headertext[j]);
    } 
  }
}

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

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Validation of Email Existence (Using Django and Javascript/Ajax)

I'm currently facing a challenge with building an E-mail validator using Django and Javascript/Ajax. Despite my efforts, I seem to be stuck at a certain point where the Ajax response consistently shows: {response: "This field is required.", email: fa ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...

Removing an Element in a List Using Jquery

In my JQuery, there is a list named additionalInfo which gets populated using the function below: $('#append').on('click', function () { //validate the area first before proceeding to add information var text = $('#new-email&a ...

Using CSS Clip Path to conceal elements

My current design uses clip-path for a gradient effect at the top of the page. Ideally, I want the two angles to meet seamlessly without any visual issues. I initially positioned the top so that they touch perfectly and nothing interferes with the angled ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

Issue with Backbone.Marionette: jQuery document.ready not executing when on a specific route

I am dealing with a situation in my web application where the document.ready() block is not being executed when the page routes from the login button to the dashboard. I have an initialize() function that contains this block, but it seems like there is an ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

The slider spills over the edges of the page

Seeking assistance – I managed to insert this logo slider onto my page. It seems to be functioning properly, but due to the width settings of the website engine, the modules are not fully stretching across the page. In an attempt to make the slider cove ...

Vue.js axios method returns undefined; v-for directive fails to iterate - Issue on Wordpress site

Using a shortcode, I have integrated Vue.js into a Wordpress page. pl2010_vue_init_directory = pl2010_vue_init_directory || (function(ctx) { new Vue( { el: '#'+ctx.el, data: { errorMsg: "", successMsg: "", show ...

Exploring NodeJS Express Routing Across Various URIs/URLs

In my application, there is a public folder that contains HTML/CSS3/JS code. This folder has two main parts: one with the public facing index.html inside public/web and another with an admin view exclusively for admins. Below is the basic layout: public ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Modifying the color of the highlighted selection in a dropdown select box

Is it possible to change the blue highlight on this dropdown to gray? Check out this demo of a select box I am aiming to alter the highlight color to gray, can someone help me achieve this? select { border: 0; color: #EEE; background: transparen ...

Clicking on the ActionButton will trigger the sending of an HTTP Request in this Firefox

Seeking guidance: As I develop an addon, my objective is to initiate a HTTP request upon clicking the ActionButton. The data to be sent to the server includes the URL of the tab and the content of the page. Initially, I attempted to create a log message a ...

Changing the text color of Material UI Accordion Summary upon expansion

How can I update the color of an Accordion summary text in Material UI when it is expanded? <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')} className={classes.root}> <AccordionSummary ...

What is the best way to use CSS 3 to resize and enlarge an image, such as sprite icons?

Hello everyone, Picture this: a sprite image named icons.png linked to the css class .icons, featuring various 10x10px graphics. Now imagine needing another class that enlarges these sprite graphics exactly twice their size, making them 20x20 pixels on the ...

Sinon - using callbacks in stubbed functions leading to test method exceeding time limit

One of my express route methods is structured as follows: exports.register_post = function(req, res) { var account = new Account(); account.firstName = req.param('firstName'); //etc... account.save(function(err, result) { ...