The following code shows an example of the setAttributeNode() method in JavaScript.
Programmingempire
Demonstrating Example of the setAttributeNode() Method in JavaScript
The following HTML code demonstrates the usage of setAttributeNode() method. Basically, we use this method to set an attribute node for an HTML element. As can be seen in the code, there is a paragraph that has onmouseover attribute. When a user moves the mouse over this paragraph, the function f1() gets executed. This function creates a style attribute using the createAttribute() method. Further, it sets the value of the style attribute. After that, it calls the setAttributeNode() method for the paragraph. When the user moves the mouse over it, the style of paragraph is changed.
<html>
<head>
<title>setAttributeNode Method Demo</title>
<script>
function f1()
{count=1;
var x1=document.getElementById("p1");
var x2=document.createAttribute("style");
x2.value='color:#aa33af;text-align:center;width:500px;';
x1.setAttributeNode(x2);
}
</script>
<style>
.c1{
border: 4px solid #33ff99;
border-radius: 10px;
background-color: #5566aa;
color: #aaffff;
font-size: 20px;
text-align: center;
margin:5px;
padding: 10px;
}
.a1{
margin: 50px;
}
.c2{
background-color: #ddeeff;
color: #ff5566;
font-size: 25px;
text-align: left;
margin:40px;
padding: 5px;
width: 800px;
}
</style>
</head>
<body>
<div id="d1" class="c2"><br/><br/>
Example of setAttributeNode() Method<br/>
<br/>
<p id="p1" onmouseover="f1()">It is a Sample Paragraph.
Move the mouse over it to set its style</p>
<br/>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020