revision:
The Document.createAttribute() method creates a new attribute node, and returns it. The object created is a node implementing the Attr interface. The DOM does not enforce what sort of attributes can be added to a particular element in this manner.
document.createAttribute(name)
Parameters:
name : required; a string containing the name of the attribute to be created.
const node = document.getElementById("div1");
const a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my_attrib")); // "newVal"
function myFunction() {
const att = document.createAttribute("class");
att.value = "democlass";
document.getElementsByTagName("h1")[0].setAttributeNode(att);
}
const att = document.createAttribute("style");
att.value = "color:red";
const h1 = document.getElementsByTagName("h1")[0];
h1.setAttributeNode(att);
example: click "Add" to create a class attribute and add it to the first h4 element
<div>
<h4>The first h4 heading</h4>
<h4>The second h4 heading</h4>
<h4>The third h4 heading</h4>
<button onclick="addFunction()">Add</button>
</div>
<style>
.democlass {color: red;}
</style>
<script>
function addFunction() {
// Create a class attribute:
const att = document.createAttribute("class");
// Set a value of the class attribute
att.value = "democlass";
// Add the class attribute to the first h1;
document.getElementsByTagName("h4")[0].setAttributeNode(att);
}
</script>
example: create a style attribute that adds a red color to the h4 element.
<div>
<h4>The fourth h4 heading</h4>
<h4>The fifth h4 heading</h4>
</div>
<script>
// Create a class attribute:
const att1 = document.createAttribute("style");
// Set the value of the class attribute
att1.value = "color:red";
// Add the class attribute to the first h1;
const h4 = document.getElementsByTagName("h4")[4];
h4.setAttributeNode(att1);
example: add a "href="www.lwitters.com" attribute to an anchor element.
Click "Add" to add a href attribute to the anchor above.
<div>
<a id="myAnchor2">Go to lwitters.com</a>
<p>Click "Add" to add a href attribute to the anchor above.</p>
<button onclick="goFunction()">Add</button>
</div>
<script>
function goFunction() {
// Create a href attribute:
const attr = document.createAttribute("href");
// Set the value of the href attribute:
attr.value = "https://www.lwitters.com";
// Add the href attribute to an element:
document.getElementById("myAnchor2").setAttributeNode(attr);
}
</script>