skip to Main Content

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:

<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>

2

Answers


  1. You could add the event to an eventlistener and switch the text on click.

    const btn = document.getElementById("btn");
    
    btn.addEventListener('click', function() {
        btn.innerHTML = { text1: 'text2', text2: 'text1' }[btn.innerHTML];
    });
    <button id="btn">text1</button>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search