Skip to content
Advertisement

Why is Javascript loading only once?

Please refer to the following SCRIPT

<html>
  <style>
     #div_content {
        height: 200px;
        width: 200px;
        background-color: yellow;
        position: relative;
     }
     #btn_addContent{
       position: absolute;
       left: 0;
       bottom: 0;
     }
    #btn_removeContent{
       position: absolute;
       right: 0;
       bottom: 0;
     }
  </style>

  <body>
     <div id="div_content">
       <p> Existing Content </p>
       <button id="btn_addContent">Add Content </button>
       <button id="btn_removeContent">Remove Content </button>
     </div>
     
  </body>

  <script>
      var divElement = document.getElementById("div_content");

      function addContent(){
         divElement.innerHTML = divElement.innerHTML + "<P> New Content </p>";
      }

      function removeContent(){
         divElement.parentNode.removeChild(divElement);
      }


      var btnAddContent= document.getElementById("btn_addContent");
      btnAddContent.onclick = addContent;

      var btnRemoveContent = document.getElementById("btn_removeContent");
      btnRemoveContent.onclick = removeContent;
      
  </script>

</html>

While running this script, any of the function is running that too only once means Javascript is loading only once kindly do the needful. i.e., if I want to addcontent I am able to add it single time and at the same time means on the same page if at all I want to remove the div_content section I am not able to do so, but, on fresh reload I’m able to remove the div_content section that is for every reload I can only do add or remove not both and not even multiple adding.

Advertisement

Answer

innerHTML += will destroy all the child elements reference(Remove and add again in DOM tree).

Use .appendChild

From MDN, innerHTML removes all of element’s children, parses the content string and assigns the resulting nodes as children of the element.

var divElement = document.getElementById("div_content");

function addContent() {
  var elem = document.createElement('p');
  elem.textContent = 'New Content';
  divElement.appendChild(elem);
}

function removeContent() {
  divElement.parentNode.removeChild(divElement);
}
var btnAddContent = document.getElementById("btn_addContent");
btnAddContent.onclick = addContent;
var btnRemoveContent = document.getElementById("btn_removeContent");
btnRemoveContent.onclick = removeContent;
#div_content {
  height: 200px;
  width: 200px;
  background-color: yellow;
  position: relative;
}
#btn_addContent {
  position: absolute;
  left: 0;
  bottom: 0;
}
#btn_removeContent {
  position: absolute;
  right: 0;
  bottom: 0;
}
<div id="div_content">
  <p>Existing Content</p>
  <button id="btn_addContent">Add Content</button>
  <button id="btn_removeContent">Remove Content</button>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement