Subscribe

Vanilla JavaScript toggleAttribute

โœ๏ธ

Learn how to toggle between two attributes in Vanilla JavaScript. See the code examples in the Codepen!

14 Jul, 2020 ยท 2 min read

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

<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

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

View the toggleAttribute method in action here:

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

Browser Support

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!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1829 devs and subscribe to my newsletter