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:

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

Does text alignment apply to one tag but not the other?

Hello, I am in the process of creating a basic webpage and encountering some formatting issues. When I apply the style format to one element, it aligns perfectly, but for another element it doesn't seem to be working. I'm certain it's a simp ...

$_POST is unable to read POST parameters when using AJAX

I've been facing an issue with sending data to my PHP script. Interestingly, everything works smoothly when using POSTMAN and the results are displayed correctly. However, when attempting to send the data through AJAX in my HTML project, the PHP scrip ...

Ways to eliminate an item from an array when the value of the object is not present

I am facing an issue with removing objects from an array that do not contain the data object. I have attempted to use the filter method but have not been successful. results.filter(obj => obj.data === undefined) results = [ {id: 1, location: 'a&a ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

How to perfectly align an element within a div using Bootstrap

Utilizing bootstrap here. Currently trying to center the h1 element within the div, but so far I have been unsuccessful. It consistently remains aligned to the left. Attempts have included using bootstrap's center-block helper class, as well as the fl ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

Is it possible for flex-grow to affect images? What steps can I take to identify any issues within my code?

<section> <div class="section-header"> <h5>Discover Our Team</h5> <h1>Meet the Experts</h1> <h5>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt, eaque.</h5> ...

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

Make sure to load the HTML content before requesting any input from the user through the prompt function

Could you please help me with a question? I'm looking to load HTML content before prompting the user for input using JavaScript's prompt() function. However, currently the HTML is only loaded after exiting the prompt. Below is the code that I hav ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

"Creating a duplicate of an element by utilizing the `next`

I have a dilemma involving two divs within a section of my project - one div is dynamically created while the other exists statically. My goal is to transfer the non-dynamically created div into the one that is generated dynamically. let adContainer = $ ...

Leveraging icons with Bootstrap 4.5

I am currently exploring how to incorporate Bootstrap 4.5 icons using CSS. Do you have any examples of code that could guide me on how to achieve this? I am specifically interested in understanding the required CSS declarations that would allow me to use t ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...