Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check content of button with JS in if function

I’m trying to check if button contains certain string when I click on it, and if it contains, for example "text1" I want to replace it with "text2" and vice versa.
Thank you in advance.

Edit:
To simplify everything, how can I change the text of button if it contains certain word when I click on it.

Here is the sample code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<html>
<body>
   <button id="btn">text1</button>
   <p id="result"></p>
   <script>
      let btn = document.getElementById("btn");
      let content = btn.innerHTML;

      document.getElementById("btn").onClick=function(){
          if(content.trim()==="text1"){
      document.getElementById("btn").innerHTML ="text2";
          } 
      }
      </script>
</body>
</html>

>Solution :

This should toggle the button text as expected. The content variable does not update.

<html>
<body>
   <button id="btn">text1</button>
   <p id="result"></p>
   <script>
      let btn = document.getElementById("btn");
      let content = btn.innerHTML;
      
      document.getElementById("btn").onclick=function(e){
          const content = e.target.innerHTML
          
          if (content === "text1") {
            e.target.innerHTML = "text2"
          } else {
            e.target.innerHTML = "text1"
          }
      }
      </script>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading