简体   繁体   中英

Dynamically adding content to table using Vanilla JS

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> 

Of course, you can also use appendChild to construct the list bit by bit in the client rather than adding the whole list at once. This might look like:

 const myList = document.getElementById("list"); const helloWorlds = { spanish: '¡Hola Mundo!', polish: 'Witaj świecie!', french: 'Bonjour le monde!' } const helloWorldsKeys = Object.keys(helloWorlds); for (let i = 0; i < helloWorldsKeys.length; i++) { let listItem = document.createElement('li'); listItem.classList.add('listItem'); listItem.innerHTML = helloWorlds[helloWorldsKeys[i]]; myList.appendChild(listItem); } 
 <div> <h1>Hello World!</h1> <ul id="list"></ul> </div> 

Here's an example using a table:

 const myTableBody = document.getElementById("my-table-body"); const helloWorlds = { spanish: '¡Hola Mundo!', polish: 'Witaj świecie!', french: 'Bonjour le monde!' } const helloWorldsKeys = Object.keys(helloWorlds); for (let i = 0; i < helloWorldsKeys.length; i++) { // create a table row element let tableRow = document.createElement('tr'); // create a table cell (td) element let listItem = document.createElement('td'); listItem.classList.add('listItem'); // add content to table cell element listItem.innerHTML = helloWorlds[helloWorldsKeys[i]]; // append table cell to table row tableRow.appendChild(listItem); // append table row to table body myTableBody.appendChild(tableRow); } 
 <table border="1"> <thead> <td>Hello World!</td> </thead> <tbody id="my-table-body"></tbody> </table> 

Regarding your specific application, check out this answer if you want to explore creating HTML documents and appending their contents to other HTMl documents: Cannot append DOM element to DIV node: Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node'

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM