Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptHTML DOM toggleAttribute() Method

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 the attribute name is present, and false otherwise.

Example: In this example, we will toggle the attribute of the 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.

HTML




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


Output: In this output, you can see that after clicking on the button, the attribute of the 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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments