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 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter