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:
xxxxxxxxxx
1
var myElement = document.querySelector('#element-id'); // get element by id
2
3
myElement.setAttribute(attributeName, attributeValue); // add attribute to the element
Example 1
In this example, we will add class
attribute to the myDiv
element using setAttribute()
method.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.blue {
6
background: lightblue;
7
}
8
</style>
9
</head>
10
<body>
11
<div id="my-div">This is my div.</div>
12
<script>
13
var myDiv = document.querySelector('#my-div'); // get element by id
14
myDiv.setAttribute('class', 'blue'); // add attribute class with 'blue' value
15
</script>
16
</body>
17
</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.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
div {
6
margin: 5px 5px 5px 15px;
7
width: 100px;
8
height: 100px;
9
border: 1px solid black;
10
border-radius: 10px;
11
background: lightgray;
12
}
13
14
.red-class {
15
background: red;
16
}
17
18
.green-class {
19
background: green;
20
}
21
22
.blue-class {
23
background: blue;
24
}
25
26
</style>
27
</head>
28
<body>
29
<button onclick="colorRed()">red</button>
30
<button onclick="colorGreen()">green</button>
31
<button onclick="colorBlue()">blue</button>
32
<div id="my-div"></div>
33
34
<script>
35
var myDiv = document.querySelector('#my-div');
36
37
function colorRed(){
38
myDiv.setAttribute('class', 'red-class');
39
}
40
41
function colorGreen(){
42
myDiv.setAttribute('class', 'green-class');
43
}
44
45
function colorBlue(){
46
myDiv.setAttribute('class', 'blue-class');
47
}
48
</script>
49
</body>
50
</html>