Search code examples
javascripthtmldominnerhtml

can't update a div inside another div element with innerHTML method?


    <!DOCTYPE html>
<html>
<head>
    <title>Business Card</title>
    <script type="text/javascript">
        window.onload = init;
        function init(){
        var button = document.getElementById("populateFields");
        button.onclick = updateFields;
        }
        function updateFields(){
        document.getElementById("businessCard").innerHTML = "Business Card Info";
        document.getElementById("name").innerHTML = "Name";
        }
    </script>
</head>
<body>
<div id="businessCard">
<div id="name"></div>
</div>
<input type="button" value="populate fields" id="populateFields">
</body>
</html>

I can see div with id, 'businessCard' updated with "Business Card Info" but, I the div inside that with id 'name' is not getting updated.


Solution

  • innerHTML on outer div clears out your inner div . save the inner div before using innerHTML on outer div.

      window.onload = init;
    
      function init() {
        var button = document.getElementById("populateFields");
        button.onclick = updateFields;
      }
    
      function updateFields() {
        //save inner div
        var innerdiv = document.getElementById("name");
        innerdiv.innerHTML = "Name";
    
        var outerdiv = document.getElementById("businessCard");
        outerdiv.innerHTML = "Business Card Info";
        // add inner div back
        outerdiv.appendChild(innerdiv);
    
      }
    <div id="businessCard">sme
      <div id="name">fdfdf</div>
    </div>
    <input type="button" value="populate fields" id="populateFields">