HTML | DOM createAttribute() Method

This createAttribute() method is used to create an attribute with the specified name and returns the attribute object. The attribute.value property is used to set the value of the attribute and the element.setAttribute() method is used to create a new attribute for an element. This method() contains the name of the created attribute as a parameter values.

Syntax:

document.createAttribute( attributename )

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>DOM createAttribute Method</title>
        <style>
            .gfg {
                color: green;
                font-weight:bold;
                font-size:50px;
            }
            body {
                text-align:center;
            }
        </style>
    </head>
    <body>
        <h1>GeeksforGeeks</h1>
        <h2>DOM createAttribute() Method</h2>
        <button onclick="geeks()">Submit</button>
        <script>
        function geeks() {
            var tag_name =
                document.getElementsByTagName("h1")[0];
            var attr = 
                document.createAttribute("class");
            attr.value = "gfg";
            tag_name.setAttributeNode(attr);
        }
        </script>
    </body>
</html>                 

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <style>
            h1 {
                color:green;
            }
            body {
                text-align:center;
            }
        </style>
    </head>
    <body>
        <h1>GeeksforGeeks</h1>
        <h2>DOM createAttribute() Method</h2>
        <a id="gfg">Visit GeeksForGeeks...</a><br><br>
        <button onclick="geeks()">Submit</button>
        <script>
            function geeks() {
                var id= document.getElementById("gfg");
                var new_attr = document.createAttribute("href");
                new_attr.value = "#";
                id.setAttributeNode(new_attr);
            }
        </script>
    </body>
</html>                    

chevron_right


Output:

Supported Browsers: The browser supported by DOM createAttribute() method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.