HTML DOM setAttribute(), getAttribute() and removeAttribute() Methods

setAttribute() :

The setAttribute() methods are used to add the attributes and attribute values to an element. The syntax of setAttribute() is as follows :
  element.setAttribute(attributeName, attributeValue);
where attributeName is name of the attribute you want to set and attributeValue is value of the that attribute. Lets see an Example :
<html>
<body>
  <p>Hello world This is Test Paragraph</p>
  <script>
    var elem = document.getElementsByTagName('P');
    elem[0].setAttribute('id', 'para1');
    elem[0].setAttribute('class', 'mytext');
    elem[0].setAttribute('style', 'background-color:orange;font-weight:bold;')
    </script>
</body>
</html>
Output :

Hello world This is Test Paragraph

Also note that if the specified attribute already exists, only the value is set or changed.

getAttribute() :

The getAttribute() method is used to get the value of attribute with the specified name, of an element. The syntax of getAttribute() is as follows :
  element.getAttribute(attributeName);
where attributeName is name of the attribute you want to get the value from. Now lets see an example :
<html>
<body>
  <p id="para2" class="mytext" style="color: blue;">This is Test Paragraph</p>
  <button onclick="myfunc()">Click Here</button>
  <div></div>
  <script>
    function myfunc() {
      var elem = document.getElementsByTagName('P');
      var text = "Paragraph Attribues : " + "Id : " + elem[0].getAttribute('id');
      text += "Class : " + elem[0].getAttribute('class');
      text += "Style : " + elem[0].getAttribute('style');
      document.getElementsByTagName('div')[0].innerHTML = text;
    }
  </script>
</body>
</html>
Output :

This is Test Paragraph



removeAttribute() :

The removeAttribute() method is used to removes the specified attribute from an element. The syntax of removeAttribute() is as follows :
  element.removeAttribute(attributeName);
Example :
<html>
<body>
  <p id="para3" class="mytext" style="background-color: orange;font-weight:bold;">This is Test Paragraph</p>
  <button onclick="myfunc()">Click Here</button>
  <script>
    function myfunc() {
      var elem = document.getElementsByTagName('P')[0].removeAttribute('style');
    }
  </script>
</body>
</html>
Output :

This is Test Paragraph


At above example the myfunc() will remove the style attribute from the <p>.

Next Topic :