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