EN
JavaScript - add element attribute
0
points
In this article, we would like to show you how to add an attribute to the element / node in JavaScript.
Quick solution:
var myElement = document.querySelector('#element-id'); // get element by id
myElement.setAttribute(attributeName, attributeValue); // add attribute to the element
Practical examples
Example 1
In this example, we will add class
attribute to the myDiv
element using setAttribute()
method.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<head>
<style>
.blue {
background: lightblue;
}
</style>
</head>
<body>
<div id="my-div">This is my div.</div>
<script>
var myDiv = document.querySelector('#my-div'); // get element by id
myDiv.setAttribute('class', 'blue'); // add attribute class with 'blue' value
</script>
</body>
</html>
Example 2
In this example, we will add class
attribute to the myDiv
element using setAttribute()
method. The class value will be assigned depending on which button is clicked.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 5px 5px 5px 15px;
width: 100px;
height: 100px;
border: 1px solid black;
border-radius: 10px;
background: lightgray;
}
.red-class {
background: red;
}
.green-class {
background: green;
}
.blue-class {
background: blue;
}
</style>
</head>
<body>
<button onclick="colorRed()">red</button>
<button onclick="colorGreen()">green</button>
<button onclick="colorBlue()">blue</button>
<div id="my-div"></div>
<script>
var myDiv = document.querySelector('#my-div');
function colorRed(){
myDiv.setAttribute('class', 'red-class');
}
function colorGreen(){
myDiv.setAttribute('class', 'green-class');
}
function colorBlue(){
myDiv.setAttribute('class', 'blue-class');
}
</script>
</body>
</html>