What is the best way to implement a table using JavaScript?

I am struggling to add a table to my HTML document dynamically using JavaScript.

Despite trying various methods like appendChild and insertBefore, I have not been successful.

Below is the snippet of my JavaScript code:

//JavaScript code here...

Here is the structure of my HTML:

<div class="tabs" id="tabs1">
  <!-- Table structure here... -->
</div>

// Additional HTML code for the table...

I want to insert the dynamically created table in my div with the ID "tabs1", specifically within the tbody element. However, it always appears after the tbody.

The issue seems to be that despite creating a separate div for the JavaScript content, it does not get appended inside it. My goal is to ensure the JavaScript-generated table goes into the designated div with the ID "tabs1".

Answer №1

It is not possible to include a <div> within a table body, therefore it must be placed outside along with your inserts. By modifying the code as follows:

var element = document.getElementById("tabs1")[0];
element.appendChild(row);

to:

var element = document.getElementById("tbody");
element.appendChild(row);

it appears to function correctly to some extent. View for reference: https://jsfiddle.net/KIKO_Software/kqr48uxj/4/

The new rows are now successfully added to the table body.

Answer №2

A range of concerns...

It's not permissible to include a <div> inside a <tbody> element according to the rules of HTML, so my suggestion would be to eliminate the <div>. Additionally, keep in mind that it is possible to have multiple <tbody> tags within a single <table>, allowing you to separate them into different sections with distinct id attributes.

The method call of document.getElementById("tabs1") will retrieve a single object, not an array - hence there is no need for adding [0] at the end.

var element = document.getElementById("tabs1");

Lastly, your for loop goes from 0 to 99 but the data available only spans from 0 to 1 (or 0 to 7 based on the commented out data)... and since you are attempting to access utilisateur[i], if the value of i surpasses the total number of items in the array, an error message will be displayed in the developer console. Thus, make sure to check if there are adequate items in utilisateur.length.

if (i < utilisateur.length) {
  cell0.innerText = utilisateur[i].id;
  cell1.innerText = utilisateur[i].checked
  ...
}

var utilisateur = [
  {
    id: 51,
    checked: false,
    prenom: "Dolores",
    date: "Fermière",
    examen: "host",
    note: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3344441d575c5f5c41564073545e525a5f1d505c5e">[email protected]</a>"
  },
  {
    id: 52,
    checked: true,
    prenom: "Bernard",
    date: "Robopsycologue",
    examen: "human",
    note: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cece97dbdccbd7d8cbddf9ded4d8d0d597dad6d4">[email protected]</a>"
  }
];

for (let i = 0; i < 100; i++) {
  var row = document.createElement("tr");
  var cell0 = document.createElement("td");
  var cell1 = document.createElement("td");

  var atr = document.createAttribute("class");
  atr.value = "bs-checkbox";
  cell1.setAttributeNode(atr);
  var para = document.createElement("input");
  var para1 = document.createAttribute("data-index");
  var para2 = document.createAttribute("name");
  var para3 = document.createAttribute("type");
  para1.value = "0";
  para2.value = "btSelectItem";
  para3.value = "checkbox";
  para.setAttributeNode(para1);
  para.setAttributeNode(para2);
  para.setAttributeNode(para3)
  cell1.appendChild(para);

  
  //Repeated lines are shown above

$(document).ready(function(){
    $(cell1).toggleClass("bs-checkbox");
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" class="table"
            data-toggle="table"
            data-search="true"
            data-filter-control="true" 
            data-show-export="true"
            data-click-to-select="true"
            data-toolbar="#toolbar">
  <thead>
     <tr>
        <th id="0" style="visibility: hidden; display: none;"></th>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="prenom" data-filter-control="input" data-sortable="true">Prénom</th>
        <th data-field="date" data-filter-control="select" data-sortable="true">Date</th>
        <th data-field="examen" data-filter-control="select" data-sortable="true">Examen</th>
        <th data-field="note" data-sortable="true">Note</th>
     </tr>
  </thead>
  <tbody id="tbody">
     <tr>
        <td id="1" style="visibility: hidden; display: none;"></td>
        <td class="bs-checkbox ">      <input data-index="0" name="btSelectItem" type="checkbox">      </td>
        <td>Valérie</td>
        <td>01/09/2015</td>
        <td>Français</td>
        <td>12/20</td>
     </tr>
  </tbody>
</table>

Answer №3

If you're looking for a simple solution, consider utilizing ES6 string interpolation.

Let's say we have an array of objects:

employees: [
 {
    name: 'John Doe',
    phone: '00000000',
 },
 {
   name: 'George Daniels',
   phone: '11111111',
 }
]

Now, imagine we also have an HTML table object.

To append rows dynamically, you can follow this pattern:

for (let employee of employees) {
    let row = document.createElement("tr");
    row.innerHTML = `<td>${employee.name}</td>
                     <td>${employee.phone}</td>`;
    table.appendChild(row);
   }

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

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

The Bootstrap command to show the modal with the ID "myModal" is malfunctioning

For some reason, I am having trouble with all the modal functions not working properly. I have checked the version and the load, and everything seems to be fine. An error message that keeps popping up is: Uncaught TypeError: $(...).modal is not a functio ...

Applying CSS transformations to scale up a div within its parent body

Having an issue with formatting an anchor link using transform scale attributes on hover. The link is inside a div that's aligned to the right, and I want it to enlarge when hovered over. However, this increase in size also affects the parent div, ca ...

Can you tell me why the jquery datepicker control is only loading a portion of the CSS?

Working on a new C#/ASP.Net application and I decided to incorporate the datepicker control that I've used before. I transferred all the necessary components from my previous app to this one. The appearance of the datepicker in the old app was like th ...

Modifying a variable when a specific number of elements are clicked using jQuery

I have created a script for my portfolio that is functional but I want to streamline it so that I only need to edit the HTML, not the script itself. The main requirements for the code are: Count the number of <img> tags within the element with id ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

Using HTML5 validation on a form along with a button that triggers a JavaScript function to send an email via PHP and display a modal upon

When I click the button on my website's form, a JS function is triggered to take the inputs from the form and send an email using PHP. After the email is sent, a modal popup appears thanking the user for contacting. Everything works perfectly until I ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Toggle multiple buttons based on the data fetched in the created() lifecycle hook

I have several toggle buttons that should be selected based on the values present in the response obtained through the created() method. <li> <input v-on:click="toggleCheckbox($event)" ...

What could be the reason for my regex succeeding on the client side but failing on the server side

I have implemented a regex pattern to validate usernames, ensuring they only contain English letters, numbers, and underscores. The client-side code works perfectly, preventing any input other than these characters: <input type="text" name ...

Spacing the keyboard and input field in React Native

Is there a way to add margin between the input and keyboard so that the bottom border is visible? Also, how can I change the color of the blinking cursor in the input field? This is incorrect https://i.sstatic.net/Jsbqi.jpg The keyboard is hidden https: ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

Stripe: Either a source or customer must be provided

I've been working on incorporating Stripe into my online shopping cart project, but I've hit a roadblock. Whenever I try to submit the checkout form, I keep encountering the error message: "Must provide source or customer." I suspect there might ...

Avoid retrieving data during the fetching process

I have been working on an application that utilizes Redux for state management. Furthermore, I have been using the native fetch method to fetch data. return fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json()); Within my React co ...

Stopping the execution in JavaScript: Is there a way to do it?

Here is a link with embedded JavaScript code: <a style="padding: 5px;" onclick="confirmMessage(); $('contact_693_').show(); $('errors_693_').hide(); this.hide(); $('dont_693_').show();; return false;" id="the_link_693_" hr ...

Creating HTML email forms without needing to use Outlook

We're currently looking into various options for sending forms via email. (None of us are HTML experts, we're more familiar with VB.net.) Here is the code I came across and was able to understand: <!DOCTYPE html> <html> <body> ...

Accessing JSON data from an external file using AngularJS's $http method

I am new to Angular and not very comfortable with JavaScript. I am attempting to create an app using the Ionic framework. I have successfully retrieved a list from a JSON file stored in a variable, but now I am trying to use $http.get() to fetch it from a ...

Synced Slideshows

Currently experimenting with the Owl Carousel plugin to create multiple synced carousels using their demo at the link below. However, I'm facing a specific issue when dealing with different numbers of small items in each carousel. I've successfu ...

Surprising Vercel Production Problem: Functions in Development Environment but Fails in Production Even After Reverting to a Functional Commit

In the development environment, everything runs smoothly without any issues. However, when the application is deployed to production, errors start cropping up. What's puzzling is that even after reverting to a previous commit where the production was ...