Skip to content
Related Articles

Related Articles

Improve Article
HTML | DOM toggleAttribute() Method
  • Last Updated : 29 May, 2020

The toggleAttribute() method of the element interface toggles a Boolean attribute on the given element. Attributes of an element can be changed using this method.

Syntax:

Element.toggleAttribute("attribute_name");

Parameters: 

  • Name_of_attribute: Name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.

Return Value: It returns true if attribute name is present, false otherwise.

Example: In this example, we will toggle attribute of input element to readonly. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.






<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <title>ToggleAttribute</title>
    <script>
  
        function change() {
            var input = 
            document.querySelector("input");
              
            input.toggleAttribute("readonly");
        }
    </script>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <input class="input" 
        value="This is editable">
  
    <button onclick="change()">
        Click to change attribute
    </button>
</body>
  
</html>

Output:

In this output, you can see that after clicking on button , attribute of input element changes to “readonly”, Hence it becomes uneditable.

Supported Browsers: The browsers supported by DOM toggleAttribute() method are listed below:

  • Google Chrome
  • Firefox
  • Apple Safari
  • Opera
My Personal Notes arrow_drop_up
Recommended Articles
Page :