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 value. 

Syntax:

document.createAttribute( attributename )

Example: In this example, we will use the createAttribute() method.

HTML




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


Output:

Example 2: In this example, we will use the createAttribute() method.

html




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


Output:

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

  • Google Chrome 1
  • Edge 12
  • Firefox 44
  • Opera 12.1
  • Safari 1


Contact Us