revision:
The setAttribute() method sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
To get the current value of an attribute, use getAttribute(); to remove an attribute, call removeAttribute().
element.setAttribute(name, value)
Parameters:
name : a string specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document.
value : a string containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.
<button>Hello World</button>
<script>
const button = document.querySelector("button");
button.setAttribute("name", "helloButton");
button.setAttribute("disabled", "");
</script>
<div>
<button>Hello World</button>
</div>
<script>
const button = document.querySelector("button");
button.setAttribute("name", "helloButton");
button.setAttribute("disabled", "");
</script>
Click "Add Class" to add a class attribute to the h4 element:
<div>
<h4 id="myH4">The Element Object</h4>
<p>Click "Add Class" to add a class attribute to the h1 element:</p>
<button onclick="addClass()">add class</button>
</div>
<script>
function addClass() {
document.getElementById("myH4").setAttribute("class", "democlass");
}
</script>
<style>
.democlass {color: red;}
</style>
Click "Change" to change the input field to an input button.
<div>
<input id="myInput" value="OK">
<p>Click "Change" to change the input field to an input button.</p>
<button onclick="changeAttribute()">change</button>
</div>
<script>
function changeAttribute() {
document.getElementById("myInput").setAttribute("type", "button");
}
</script>
Click "add" to add an href attribute to the element above.
<div>
<a id="myAnchor">Go to lwitters.com</a>
<p>Click "add" to add an href attribute to the element above.</p>
<button onclick="addAttribute()">change</button>
</div>
<script>
function addAttribute() {
document.getElementById("myAnchor").setAttribute("href", "https://www.lwitters.com");
}
</script>