HTML DOM setAttributeNode() Method


The DOM setAttributeNode() method set an attribute specified in its parameter to a specified element in an HTML document and return the value as an Attr Node Object.

Syntax

Following is the syntax −

node.setAttributeNode(attributeNode);

Example

Let us see an example of setAttributeNode() method −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   html{
      height:100%;
   }
   body{
      text-align:center;
      color:#fff;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
      height:100%;
   }
   .btn{
      background:#0197F6;
      border:none;
      height:2rem;
      border-radius:2px;
      width:35%;
      margin:2rem auto;
      display:block;
      color:#fff;
      outline:none;
      cursor:pointer;
   }
</style>
</head>
<body>
<h1>DOM setAttributeNode() method Demo</h1>
<p>Hi! I'm a para element in HTML with some random text</p>
<button onclick="set()" class="btn">Set Attribute</button>
<script>
   function set() {
      var p=document.querySelector("p");
      var attr=document.createAttribute("style");
      attr.value="color:#db133a;font-size:1.2rem;";
      p.setAttributeNode(attr);
   }
</script>
</body>
</html>

Output

This will produce the following output −

Click on “Set Attribute” button to set style attribute to the <p> element.

Updated on: 30-Jul-2019

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements