HTML | DOM toggleAttribute() Method

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.