The dimensions of the HTML table do not adjust properly when new items are being appended using JavaScript

I utilized this HTML Code to generate a table:

<div class="noten_tabelle">
            <table id="grades_table" style="width:100%">
              <tr>
                <th>Subject</th>
                <th>Oral</th>
                <th>Exam</th>
              </tr>
              <!-- Populate content with js code -->
            </table>
          </div>  

Using Javascript, I dynamically update the table each time new values are fetched from the server. Here is the JavaScript function:

function addToTable(subject, oralScore, examScore) {

  var subjectName = getSubjectByNumber(subject);

      //Create row

      var row = document.createElement([subjectName]);
      row.setAttribute("id", [subjectName]);
      document.getElementById("grades_table").appendChild(row);

      //Columns in a row

      var cE = document.createElement("TD");
      var tE = document.createTextNode([subjectName]);
      cE.appendChild(tE);
      document.getElementById([subjectName]).appendChild(cE);

      var a = document.createElement("TD");
      var b = document.createTextNode([oralScore]);
      a.appendChild(b);
      document.getElementById([subjectName]).appendChild(a);

      var c = document.createElement("TD");
      var d = document.createTextNode([examScore]);
      c.appendChild(d);
      document.getElementById([subjectName]).appendChild(c);
}   

To clarify, the subject value is numeric and converted into a String representing the subject name such as "Mathematics" or "German".
Currently, the display looks like this:

https://i.sstatic.net/6OrLE.png

However, there are discrepancies. The subject_name "Latin" should be under "Subject", "5.8" should be under "Oral", and "11.4" should align with "Exam".
Moreover, "Vocal Ensemble" should be listed again under "Subject", "4.7" under "Oral", and an empty field under "Exam".

Additionally, here is my CSS styling:

table {
    font-family: Montserrat-Medium;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

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

If you have any insights on rectifying these inconsistencies, please feel free to share them. Any assistance would be greatly appreciated.

Answer №1

      let newRow = document.createElement("TR");
      newRow.setAttribute("id", [subject_name]);

      //Creating table cells in one line

      let cell1 = document.createElement("TD");
      let text1 = document.createTextNode([subject_name]);
      cell1.appendChild(text1);
      newRow.appendChild(cell1);

      let cell2 = document.createElement("TD");
      let text2 = document.createTextNode([mdl]);
      cell2.appendChild(text2);
      newRow.appendChild(cell2);

      let cell3 = document.createElement("TD");
      let text3 = document.createTextNode([klu]);
      cell3.appendChild(text3);
      newRow.appendChild(cell3);

      document.getElementById("grades_table").appendChild(newRow);

Answer №2

In reviewing your code, I noticed that you forgot to include the new parent table row for your newly added table cells.

To ensure proper alignment, make sure the cells are placed within a new row containing the same number of table cells.

Simply append a new tr element and place the new td cells inside it.

If you require an uneven number of cells per row, remember to use

colspan={number of columns cell will span over}
.

Would you like me to provide a code sample to help illustrate this further?

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

Looking for assistance with CSS to properly align a dozen items

UPDATE: See the current layout in this JFiddle based on feedback received from others, still a few tweaks needed. In my setup, there are 12 divs housed within one container div. These 12 divs consist of 6 text components and 6 corresponding input fields. ...

Ways to remove the line under a logo in HTML using CSS and Bootstrap

While working on a website design, I encountered an issue with the logo where it has a line of the background color under it. This is frustrating and affects the overall design. Does anyone have a straightforward solution to remove this line? I need someth ...

Can you guide me on implementing CSS Houdini in Next.js?

Exploring the world of CSS Houdini in my Next.js project has been quite an adventure. After successfully installing the necessary CSS Houdini package and css-paint-polyfill using yarn, I decided to follow the webpack guidelines provided at . Below is a sn ...

What is the best way to stream an app's data directly to a browser in real time?

My node application is currently able to read a stream from a Kafka producer and display it in real time using console.log. However, I would like to update my web application with the same real-time functionality. How can I achieve this? I typically start ...

Discover how to apply unique styles to specific HTML elements using their index values in jQuery

In the process of creating a party game similar to Tambola or Housie, I am faced with the challenge of automatically detecting and highlighting the numbers called out on each ticket in the game. For instance, if number 86 is announced, I aim to visually di ...

EU directive on cookies: What is the best way to store your preferences?

While there are numerous third-party solutions available to comply with the cookie EU directive, I prefer to learn how to implement it myself. My specific requirement is that when a user clicks on "Accept", their choice should be remembered for the entire ...

Display a loading screen with a progress bar using React Native Expo

Currently, I am diving into the world of React Native and honing my skills using Expo. One of the tasks I've tackled is creating a loading screen for my app using npm react-native-progress. However, I'm curious if there is a way to replace the de ...

What is causing this substring to not function properly in Chinese text?

What could be causing this issue with the substring function when dealing with Chinese text? I have successfully used it for other languages, but when working with Chinese characters, I am getting an empty string as a result. countryID = "奥地利 ...

Removing unnecessary keys from intricate JSON data (with the use of pure JavaScript)

I've experimented with various methods to dynamically parse and remove keys with empty values from a JSON file using JavaScript. Currently, I can successfully delete non-nested keys, except for empty strings that have a length greater than 0. My mai ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Are you able to develop a customized TestNG Listener to cater to your specific requirements?

I have developed a unique concept for a TestNG listener that meets my specific requirements. Essentially, I aim to design a custom listener that generates a report using a predefined HTML format. The crux of my idea revolves around declaring the listener ...

Error: An unexpected character was found in the Gulpfile.js

Having an issue in my Gulpfile.js: gulp.task('webpack', gulp.series(async () => { const option = yargs.argv.release ? "-p" : "-d"; execSync(`node_modules/webpack-cli/bin/cli.js ${option}`, { stdio: [null, process.stdout, proce ...

Having trouble with the :first-of-type Pseudo Class in CSS?

I have been attempting to style the first link in an li element with a specific font color. When the li element is clicked, it gains the "open" class. I've tried using both li a:first-of-type and li a:first-child pseudo-classes to achieve this, but ...

How to locate the position of an element within a multi-dimensional array using TypeScript

My data structure is an array that looks like this: const myArray: number[][] = [[1,2,3],[4,5,6]] I am trying to find the index of a specific element within this multidimensional array. Typically with a 1D array, I would use [1,2,3].indexOf(1) which would ...

Updating the URL in React and Redux

I am currently working on developing an application using React and Redux (DVA) with Ant.Design as the main framework. I am facing an issue where I need to change the URL when a user clicks on a button, and connect that URL change to a specific action so t ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

Having trouble bringing in components to my pages in ReactJS

There seems to be an issue preventing me from importing the components onto the page, resulting in this error: ERROR in ./src/pages/Home.jsx 4:0-37 Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

Filtering Images by Alt Attribute: A Comprehensive Guide

I'm working on an image gallery project that includes a search box feature. My goal is to dynamically hide images that do not have an alt attribute matching the user's search query. Despite several attempts, I keep encountering issues where all e ...