简体   繁体   中英

Error coming as “Cannot set property 'innerHTML' of null”

I am generating html table from Javascript and assign as InnerHTML to a div tag, but its giving an error:

"Uncaught TypeError: Cannot set property 'innerHTML' of null"

<html>
<body>
<div class="fieldlist-vertical-title" style="color:white;left:0px;display:none;" id="rosterlegend">Some text</div>
<script>
   function generateLegend()
       {
       var fullTable ='' fullTable='<Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD>
       <TD>01:00 to 21:30</TD></TR></Table></TR></Table>'
       document.getElementById('rosterlegend').innerHTML = fullTable
       }
   generateLegend();
</script>
</body>
</html>

Error : Uncaught TypeError: Cannot set property 'innerHTML' of null

Try changing to something like this, so we ensure the HTML DOM has completed loading first.
Use ES6 template string instead of plain strings!

 document.addEventListener('DOMContentLoaded', () => { generateLegend(); }); function generateLegend() { fullTable = `<Table> <TR> <Table> <TR bgcolor=#FF5733> <TD>MM</TD> <TD>01:00 to 21:30</TD> </TR> <TR bgcolor=#FFFFFF> <TD>EVVV</TD> <TD>09:00 to 05:30</TD> </TR> </Table> </TR> </Table>`; document.getElementById('rosterlegend').innerHTML = fullTable; } 
 <div id="rosterlegend"> <div> 

Removes new lines and extra spaces in the HTML String.

Rest of your code works fine! However it is not a god practice. Ideally you have to wait for the window to be loaded.

window.onload(){
  generateLegend();
}

 function generateLegend() { var fullTable = " <Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD><TD>01:00 to 21:30</TD></TR><TR bgcolor=#FFFFFF><TD>EVVV</TD><TD>09:00 to 05:30</TD></TR></Table></TR></Table>"; document.getElementById('rosterlegend').innerHTML = fullTable; } generateLegend(); 
 <div id="rosterlegend">Some text</div> 

Your issue is that you are trying to access your div with the id of "rosterlegend" before the DOM has loaded. This means that when your javascript tries to access your element it cannot. One way you can fix this is by adding the load or DOMContentLoaded event listener to your element, where the function will fire once your HTML (including images if you use the load event) and window has loaded. This way your javascript will know about your HTML.

See working example below:

 function generateLegend() { var fullTable = " <Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD><TD>01:00 to 21:30</TD></TR><TR bgcolor=#FFFFFF><TD>EVVV</TD><TD>09:00 to 05:30</TD></TR></Table></TR></Table>"; document.getElementById('rosterlegend').innerHTML = fullTable; } window.addEventListener("load", generateLegend); // call your function when the window has loaded 
 <div id="rosterlegend"></div> 

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