0

I want to load a custom html fetched from backend and load it into a page/iframe asynchronously. However when I load HTML with table elements, the content inside table element is moving outside of it.

let html = `
  <div>
    <table>
      <tr> 
        <ul>
          <li>Apple </li>
          <li>Banana </li>
          <li>Cat </li>
        </ul>
          
      </tr>
    </table>
  </div>
`
let s = document.createElement('html')
s.innerHTML = html;
console.log('Actual HTML', html);
console.log('Rendered HTML', s.innerHTML);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
noName94
  • 3,783
  • 1
  • 16
  • 32
  • 2
    Key is to apply valid html. If you apply invalid html the browser tries to correct it based on best effort. The results can be dodgy and can be different betweeen browsers. – Mark Baijens Jul 24 '23 at 15:12

1 Answers1

1

The results your are seeing is because you are not inserting your HTML string into the body section of the page, which is where all visible page content belongs and your table data belongs inside of a <td>.

Also, tables are actually divided into 2 sub-sections, <thead> and <tbody>. If you omit these, the <tbody> will be inserted automatically.

This is more like what you should be doing:

let html = `
  <div>
    <table>
      <tr>
        <td>
          <ul>
            <li>Apple </li>
            <li>Banana </li>
            <li>Cat </li>
          </ul>
        </td>    
      </tr>
    </table>
  </div>
`
let s = document.createElement('body');  // <-- Not HTML
s.innerHTML = html;
console.log('Actual HTML', html);
console.log('Rendered HTML', s.innerHTML);

Finally, if you want to load some page content asynchronously, you should be using an XMLHttpReqeust (AJAX) component.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71