Javascript DOM HTML Element setAttribute() Method

Introduction

Add the class attribute with the value of democlass to a <h1> element:

document.getElementsByTagName("H1")[0].setAttribute("class", "democlass");

Click the button to add a class attribute with the value of democlass to the h1 element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {//w ww. jav  a2  s.co  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>

The setAttribute() method adds the specified attribute to an element, and sets it the specified value.

If the specified attribute already exists, only the value is updated.

Use the removeAttribute() method to remove an attribute from an element.

element.setAttribute(attributename,attributevalue);

Parameter Values

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

The setAttribute() method has No return value.




PreviousNext

Related