JavaScript createAttribute method

In the HTML JavaScript we have one of the important method createAttribute which can be used to create the html tag's attribute dynamically.

JavaScript createAttribute method

JavaScript createAttribute method

     

In the HTML JavaScript we have one of the important method createAttribute which can be used to create the html tag's attribute dynamically. We can create any attribute of the tag elements by getting the object of it and then we can add value for this attribute to that element by setting the property "nodeValue" to add the node we can use the method setAttributeNode( attributeName) .

 

 

 

 

 

Syntax: 

document_Object.createAttribute("attributeName");

Description of example code:

In our this example code we have created an input text with its default size and after this we have added a button with the following caption "Create & Add attribute". This button will call the JavaScript function create() as defined in between the script tag. In this function create() we have created an attribute "size" and set its value to the "15". Here is the full example code of the createAttributeExample as follows:

createAttributeExample.html

<html>
<body>
<script language="JavaScript">
function create(){
    var attribute = document.createAttribute("size");
    attribute.nodeValue = "15"
    document.getElementById("text").setAttributeNode(attribute); 
} 
</script>
<div style="background: #cf2255; width:'100%';" align="center">
  <font color="#ffffcc" size="12pt">
           <b>Create Attribute Example</b>
   </font>
</div>
<div style="background: green width:'50%';">
	<center>
		<input type="text" id="text" value="" />
		<input type="button" 
                       value="Create & Add attribute" 
                       onclick="create(); 
                       this.disabled=true;">
	</center>
</div>
</body>
</html>

Output:

When user click on the Create and Add attribute button it sets the text box size to 15 by removing the default value of size attribute.

Download Source Code