Dynamically adding content to table using Vanilla JS

javascript add rows to table dynamically
create dynamic table in javascript
adding table rows and columns in javascript
for loop in html table using javascript
dynamically add column in html table using javascript
javascript create table from array
javascript table example code
how to display data in table in javascript

I'm trying to add as many rows as users I have in my database to a table. I'm getting the users' info from the backend via ajax request, then when the response (JSON) arrive my code pass it to I silly template I'd created using underscore.js.

After underscore rendered the template this is what i got:

<tr data-id="29">
    <td>email@themail.ma</td>

    <td>
        <ul style="display:inline-block; padding-left:0; margin-bottom:0">
            <li style="display:inline-block;"><a href="#"></a></li>
        </ul>
    </td>

    <td>Activo</td>

    <td>No caduca</td>

    <td>
        <span data-placement="left" data-toggle="tooltip" title="Eliminar usuario">
            <a class="icon-trash" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-del-user"
               data-msg="Desea eliminar el usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Cambiar contraseña">
            <a class="icon-key" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-chg-pass"
               data-msg="Cambiar contraseña del usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Bloquear usuario">
            <a class="icon-lock" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-block-user"
               data-msg="Desea bloquear el usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Desbloquear usuario">
            <a class="icon-lock-open" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-unblock-user"
               data-msg="Desea desbloquear el usuario?"></a>
        </span>

    </td>
</tr>

So far so good, but when I do something like this:

tbody.innerHTML = html;

// or 

let parseHTML = function(str) {
  var tmp = document.implementation.createHTMLDocument();
  tmp.body.innerHTML = str;
  return tmp.body.children;
};

parseHTML(html);  // and then adding the returned codes to my tbody

It just looses the html table format (td, tr tags, etc)

I often use template literals for this, constructing a long string of HTML using the += operator and then using document.innerHTML to append the final HTML string to my page.

A simple example might look like this:

const helloWorlds = {
  spanish: '¡Hola Mundo!',
  polish: 'Witaj świecie!',
  french: 'Bonjour le monde!'
}

const helloWorldsKeys = Object.keys(helloWorlds);

let listMarkup = '';

for (let i = 0; i < helloWorldsKeys.length; i++) {
  listMarkup += '<li class="listItem">' + helloWorlds[helloWorldsKeys[i]] + '</li>';
}

const myList = document.getElementById("list");

myList.innerHTML = listMarkup;
<div>
  <h1>Hello World!</h1>
  <ul id="list"></ul>
</div>

Add,Edit And Delete Rows From Table Dynamically Using JavaScript, How do you add and remove rows dynamically in a table? A pure Vanilla JavaScript based data table component that features dynamic tabular data, table filtering, sorting, paginating and many more. Install the Vanilla-DataTables: # NPM $ npm install vanilla-datatables # Bower $ bower install vanilla-datatables Basic usage: Import both Vanilla-DataTables’ JavaScript and CSS files into your project.

The problem I see here is that you're using tbody.innerHTML = html; instead of tbody.innerHTML += html;, when you use += operator you keep the old HTML, if you use = you replace the old HTML with the new HTML

Dynamically Add or Remove Table Rows in JavaScript and Save , How add or remove rows inside a table dynamically using jQuery? Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

Thanks to @jaredgorski I realized why the html code was losing the formating, so this is the solution best fit my problem so far. Any suggestion would be appreciated.

function convert2Element (strHTML) {
    let table = document.createElement('table');
    table.appendChild(document.createElement('tbody'));
    table.querySelector('tbody').innerHTML = strHTML;
    return table.querySelector('tbody tr');
}

Then I can append the returned value like and treat it like the object it is.

Traversing an HTML table with JavaScript and DOM Interfaces , How do you edit a row in a table using JavaScript? The entire process is very simple and obfuscates much of the complexity from the developer. Just add the script to your site and follow the following steps, and you'll have instant client side pagination, in under 100 lines of code. 1. Add the pagination class to each table that you want to add a pagination to. 2.

Dynamic Data Table In Vanilla JavaScript, To remove rows in the table, I'll add dynamically created buttons (using JavaScript) in each row of the table. For data entry, I'll create and add textboxes in each cell, dynamically. The second button will submit the data in the table. The first method createTable() in the script creates the table. The columns, rows and cells will be dynamically created in the Table using JavaScript. TAGs: JavaScript, HTML, JSON, Table, Arrays Here Mudassar Ahmed Khan has explained how to create a dynamic Table in HTML at runtime using JavaScript.

HTML DOM Table insertRow() Method, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Insert new row(s) at the first position of a table (and insert a <td> element with some Create an empty <​tr> element and add it to the 1st position of the table: Add some text to the new cells: Vanilla JavaScript provides two really easy ways to get and set content in the DOM—one to manipulate markup, and the other just for text. Manipulating HTML You can use the innerHTML to get and set HTML content in an element. var elem = document.querySelector('#some-elem'); // Get HTML content var html = elem.innerHTML; // Set HTML content elem.innerHTML = 'We can dynamically change the HTML.

Back To The Basics: How To Generate a Table With JavaScript, What it takes to generate a table with vanilla JavaScript? An HTML table is an element containing tabular data, presented in rows and  We have created a simple HTML form with name and age input. When the user clicks on the Add button we add a row to the Table element dynamically. You can also create a table right from scratch using createElement method. Source for the HTML page - index.html

Comments
  • I'm trying to dynamically add content to my table, the problem is when I try to parse the long string to HTML
  • I see, thanks for clarifying about the table. This should work if you're dynamically adding content on page load, though for realtime updates (without a pageload) you'll either need event listeners, a scheduler, or some sort of framework. Let me experiment and update my answer
  • @Nestor I've updated my example to show how you can use appendChild with a table. Does this help?
  • Also, just to note, there's no need to parse the HTML unless you're parsing for some security purpose or to convert from XML.
  • I don’t understand why you need to create an entire HTML document with your snippet of HTML (which isn’t really parsing it, so parseHTML is an inaccurate name) and then append that document to the DOM. If you validate/trust the data in your database, you should be able to just generate a string and add it or append it element by element. As long as you’re formatting the table properly, it won’t lose it’s formatting. That’s why the HTML you’re passing to createHTMLDocument is losing its formatting: because you’re creating a whole document that starts with <tr> tags that aren’t in a <table>.
  • I think it would be better to use tbody.appendChild(html) than +=