Element setAttribute() Method - Javascript DOM

Javascript examples for DOM:Element setAttribute

Description

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

For existing attribute, it will change the attribute value.

Parameter Values

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

Return Value:

No return value

The following code shows how to Add the class attribute with the value of "democlass" to a <h1> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {/*from  ww w .  j a  va  2  s  . c  o m*/
    color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
    document.getElementsByTagName("H1")[0].setAttribute("class", "democlass");
}
</script>

</body>
</html>

Related Tutorials