JavaScript » Functions » setAttribute

Syntax:
object.setAttribute(string)

This function is used to set the value of an attribute on an object. It is typically used along with objects returned by document.getElementById to assign a new value to the object's attribute.

Examples

Code:
<p id="myID" attr="my attribute value">

...

<script>
  var pTag1 = document.getElementById('myID');
  document.write(pTag1.getAttribute('attr') + '<br>\n');
  pTag1.setAttribute('attr', 'my new attribute value');
  document.write(pTag1.getAttribute('attr'));
</script>
Output:
my attribute value
my new attribute value
Language(s): JavaScript