1

In my case the script terminates before the html page is displayed at all. Therefore, it has no access to the HTML DOM and cannot update elements while a dialog is shown. It is a requirement.

But I need to create a table having dynamic rows and columns according to the various data , Im having

<html>
    <body style="overflow:hidden;">

        <?js
        // here the js code must be.
        // I have a json object array, I need to create a table to 
        //display these data. According to the size the table rows and 
         //columns must be changed. 
        ?>

        <!--Body div has autogenerated id.Please do not delete it. --> 
        <div id="bodydiv" class="Blank" style="background-color:rgb(247, 247, 247); height: 100%; width: 100%;">

        <!-- here the html page elements must be created -->
        </div>  

    </body>
</html>

2 Answers2

0

This is a very common issue, because :

  • javascript is appended after the html or
  • javascript is asynchronously loaded before the page as the time to load.

One way to solve this would be to run the javascript after the dom is loaded :

// your table does not exist here
console.log(document.querySelectorAll('#bodydiv table').length);
window.onload = function whenLoaded() {
   // your table exist here
   console.log(document.querySelectorAll('#bodydiv table').length);
}

This work fine in most case, even when your script is downloaded resource.

If you prefer, just add <script></script> at the end of your <body /> tag and it should also work.

Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204
0
var jsonArray;    //let's this is your json object array

var table = document.createElement("table");
for(var i=0;i<jsonArray.length;i++){

    var row = table.insertRow(i);

    //insert cells to the row based on the number of element you want to show in table from jsonArray
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);

    //Assume key1 and key2 are keys in each jsonArray object
    cell1.innerHTML = jsonArray[i].key1; 
    cell2.innerHTML = jsonArray[i].key2;      
}

document.getElementById("divId").appendChild(table);    //consider a div with id 'div1' where you want to show the table

Put the above code in your Javascript function and keep this function in <script> tag at the bottom of your body tag.

I think this is what you actually want.

S.Mandal
  • 172
  • 1
  • 10
  • I don't see how this adds to the DOM. I put it in my code and did a 'view source' -- it's not there. The only place it shows up is on the screen and in the Firefox Inspector. – McAuley Oct 06 '19 at 08:06