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

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

Creating a diagonal effect on a table using jQuery

I am interested in adding a diagonal effect to my table. For instance, if I have a 5x5 table, I want to highlight the first row and set the background color of the corresponding column in that row to red. The same should be done for each subsequent row. ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

Issue persists: Ajax functionality remains nonfunctional, prompting the need for

My goal is to use the post input, and upon hitting enter, I want to dynamically replace <div id="mainPagePosts"></div> with new data without causing a page refresh. However, even after submitting the post, the page still refreshes, although I d ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

React strict mode and Material UI console notifications

Just like a rapidly growing application can make the console as dirty as a footballer's shirt. What am I trying to convey? When using Material UI in strict mode, warnings such as FindDomNode may appear, or it may ask you to use strings instead of bo ...

Creating personalized templates in DJANGO - Efficiently linking help_text to individual fields

When creating a registration form using my own CSS and HTML, I encountered an issue with displaying error messages from Django's default help_text. Although I can show the help_text using the code below, I am having trouble associating the errors with ...

Looking for assistance with CSS border animation

Below is my code snippet: .section-one { position: relative; background: #ffffff; } .section-one h2 { color: #000000; font-size: 32px; margin: 0px 0px 10px 0px; padding: 0px; font-family: "AzoSans-Medium"; } ... /* ...

Issues with the functionality of the submit button (html, js, php)

Seeking assistance with a submit button functionality issue - I have a simple submit button that allows visitors to enter their email address. Upon clicking the button, it should add their email to a CSV file and display a pop-up thank you message. The pr ...

Encountering a 404 error while loading CSS in a Django application

I'm currently in the process of developing a chatbot application. I'm encountering issues with loading the CSS for the frontend using django's static data load feature. Here are the file paths: CSS path: C:\Documents\Django_Works ...

Execute JavaScript code once all the AngularJS template directives are fully loaded

On my HTML page, I am utilizing AngularJS template directives. Here is an example of how it looks: <div class="row"> <div class="col-sm-12"> <div logo></div> <div login-card></div> ...

Making an asynchronous request using Ajax to verify the status of a checkbox

I have two checkboxes, and I want to make an ajax call to a jsp page when one of the checkboxes is clicked. The jsp page should display a table with data fetched from a database. The issue arises when dealing with two checkboxes: <div class="search-in ...

Making a standard AJAX request using jQuery without including the XHR header

I am looking to make an ajax-type request using the following headers (or something similar): GET example.com/ajaxapi/article/1 HTTP/1.1 Host: localhost Accept: application/hal+json Cache-Control: no-cache The key aspect here is to accomplish this withou ...

"Enhance your Vue 3 experience with a stylish Instagram Feed featuring

Struggling to retrieve the most recent Instagram posts from a feed using Vue 3 and Axios due to Instagram's strict-origin-when-cross-origin policy causing constant blocks. All access tokens are properly configured. The Instagram Basic Display API gui ...

Creating a CSS Grid with Scroll Snap functionality to mimic an iPhone screen in HTML

I have created an iPhone simulator using HTML. It's in German, but I can provide a translation if needed: // JavaScript code for various functionalities related to the iPhone interface /* CSS styling for the iPhone interface */ <meta name="v ...

The content is being pushed down by the responsive navigation bar

While the navbar is in normal non-responsive mode (I'm not sure if that's the right terminology) on Chrome and you scroll down, the logo image stays behind the menu. However, when the screen width shrinks and the menu collapses, clicking the icon ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

How can I achieve transparency for an element while it is nested within multiple parent

Is there a clever method to achieve transparency for an element that allows the background of its parent element to shine through and display the body background, for example? Consider this scenario: <body style="background: url(space.jpg)"> <di ...

Monitor changes in the visible price range in lightweight-chart

Is there a way to detect when the visible price range changes in lightweight-chart, similar to how the timeScale's visible time range change can be detected through subscribeVisibleTimeRangeChange? I couldn't find anything related in the document ...