How do I remove an already set attribute and replace with another in JavaScript

231 Views Asked by At

I added an attribute to a div I created, now I want to remove this attribute and replace with another once listen to a click event. How do I do that?

I tried using the remove attribute but I don't seem to understand why it's not working...

1

There are 1 best solutions below

0
N.Nush On BEST ANSWER
  • Check if below example helps you.

  • You can skip the else condition in script if you only need to remove the attribute on click.

     <div align="center" id="div1"><p>Example</p></div>
     <button  onclick="myFunction()">Try it</button>
    
     <script>
     function myFunction() { 
        var x = document.getElementById("div1"); 
        if (x.hasAttribute("align")) { 
            x.removeAttribute("align");  
        }else{ 
            x.setAttribute("align", "right");
        } 
     }
     </script>