codeLover codeLover - 1 month ago 8
HTML Question

Unable to add data "innerHTML" to <div> tags using getElementByID()

I'm very new to HTML< Javascript concepts. So kindly go easy on me.
I created 2 tags & want to selectively add data to each div tag using their ID, onload, but the the below code isn't adding "H1" & "h2" to each div tag.
Did i miss something ?

<html>
<head>
<title>Titlehere</title>
<p> Hello></p>

</head>
<body>
<div id="tab1" onload="populatehtmlTab1()">
<p>i1</p>
</div>

<div id="tab2" onload="populatehtmlTab2()">
<p>i2</p>
</div>

<script type="text/javascript">
function populatehtmlTab1() {
document.getElementById(tab1).innerHTML = document.getElementById(tab1).innerHTML + "<p>h1</p>";
}

function populatehtmlTab2() {
document.getElementById(tab2).innerHTML = document.getElementById(tab1).innerHTML + "<p>h2</p>";
}
</script>

</body>
</html>

Answer Source

There are a few things wrong with this. Here is the code amended:

function populatehtmlTab1() {
   document.getElementById('tab1').innerHTML =  "<p>h1</p>";
 }

 function populatehtmlTab2() {
   document.getElementById('tab2').innerHTML =  "<p>h2</p>";
 }

function loadHtml(){
  populatehtmlTab1();
  populatehtmlTab2();
}
<html>
<head>
    <title>Titlehere</title>
    <p> Hello></p>

</head>
<body onload="loadHtml()">
    <div id="tab1" >
        <p>i1</p>
    </div>

    <div id="tab2">
        <p>i2</p>
    </div>

    <script type="text/javascript">
        
    </script>

</body>
</html>

First the element id selector must be a string:

document.getElementById('tab1')

second you just need to assign the innerHTML directly:

document.getElementById('tab2').innerHTML =  "<p>h2</p>";

Third you should use onload on the body, I wrapped both your functions into another function in my amended code.