Vanilla JavaScript toggleAttribute

β€” 4 minute read

permalink

In todays article we are going to learn about the JavaScript toggleAttribute() method. This method can be used to toggle a boolean attribute.

What kind of attributes? We can use the method to change a readonly value or a required value onclick of an element, for instance.

In today's topic, we will look into toggling the attribute values of readonly and required in an input element.

HTML Structure permalink

<label
>
Required + ! ReadOnly
<input id="inp-01" value="fuu" required />
</label>
<br /><br />
<label
>
! Required + ReadOnly
<input id="inp-02" value="bar" readonly />
</label>
<br /><br />
<button onclick="toggleRequired()">Toggle Required</button>
<button onclick="toggleReadOnly()">Toggle ReadOnly</button>

So, we have two inputs. The first will be by default required but not readonly and the second will be the other way around.

Then we'll add two buttons which will toggle the required and readonly attributes onclick.

JavaScript toggleAttribute permalink

For the JavaScript code we first get the two inputs and then define our two functions to change the attribute values:

const input01 = document.getElementById('inp-01');
const input02 = document.getElementById('inp-02');

function toggleRequired() {
input01.toggleAttribute('required');
input02.toggleAttribute('required');
}

function toggleReadOnly() {
input01.toggleAttribute('readonly');
input02.toggleAttribute('readonly');
}

There we go. With this JS code we can now toggle the attributes on between true and false!

See the code examples in this Codepen permalink

View the toggleAttribute method in action here:

See the Pen Vanilla JavaScript toggleAttribute by Chris Bongers (@rebelchris) on CodePen.

Browser Support permalink

The method is not supported in IE (😞), but we can use a Polyfill for it!

View on CanIUse

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter