Javascript Reference - DOM Element setAttribute() Method








The setAttribute() method adds the attribute and value to an element.

Browser Support

DOM Element setAttribute Yes 9 Yes Yes Yes

Syntax

element.setAttribute(attributename, attributevalue)

Parameters

Parameter Type Description
attributename String Required. The name of the attribute
attributevalue String Required. The value of the attribute




Return Value

No return value.

Example

The following code shows how to set the type attribute of an input element.


<!DOCTYPE html>
<html>
<body>
<!--   w w w.j  ava 2  s .  c om-->
<input value="OK">
<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementsByTagName("INPUT")[0].setAttribute("type", "button"); 
}
</script>
</body>
</html>

The code above is rendered as follows: