javascripthtmlfunctioninnerhtmlinnertext

Innerhtml keeps adding up instead of replacing it - javascript - html


I've got a pretty complicated code to explain and I'm not a native Englisch speaker so I'm trying to explain my problem with an simple example.

I've got this function (let's call it function check). I added an eventlistener to a button (let's call this button1). When the button is clicked the function is executed.

Function check () {
   if (document.getElementById("id1").hasAttribute("clicked")) {
      document.getElementById("id2").innerHTML = '<p>Hello World!</p>;
   } else {
      document.getElementById("id2").innerText = "Hello you";
   }
}

button1.addEventListener("click", check);

So here's the problem: When it doesn't have the attribute it does display "Hello you". Which is great. Click again and its still displayed only once, great again. But if than later it does have the attribute and the button is clicked again, thank it displays both "Hello you" as "Hello world!" which is not great.

What is worse, and this happens if "Hello you" is or isn't already displayed, when I click the button again it keeps adding the innerHTML so even if "Hello world" is already displayed, it just adds it underneath everytime I click the button.

Is there a way to replace the text or html code that's already there?

I've tried looking it up on the internet but I can't find a solution. I'm a beginner so I hope you can help me with a easy way to fix this


Solution

  • Check This

    function check () {
    
       if (document.getElementById("id1").hasAttribute("clicked")) {
          document.getElementById("id2").innerHTML = '<p>Hello World!</p>';
       } else {
          document.getElementById("id2").innerText = "Hello you";
       }
    }
    
    
    document.getElementById("button1").addEventListener("click", check);
    document.getElementById("button2").addEventListener("click", changeAttr);
    
    function changeAttr(){
    document.getElementById("id1").setAttribute('clicked',true)
    }
    <div id="id1"></div>
    <div id="id2"></div>
    <button id="button1">Click</button>
    <br/>
    <br/>
    <button id="button2">Add Attribute </button>