EN
JavaScript - remove 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.removeAttribute(attributeName); // remove attribute from the element
Example 1
In this example, we will remove class
attribute from the myDiv
element using removeAttribute()
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" class="blue">This is my div.</div>
12
<script>
13
var myDiv = document.querySelector('#my-div'); // get element by id
14
myDiv.removeAttribute('class'); // remove class attribute from myDiv
15
</script>
16
</body>
17
</html>
Example 2
In this example, we will remove class
attribute from the myDiv
element using removeAttribute()
method. The class value will be removed on button click.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
div {
7
margin: 5px 5px 15px 20px;
8
width: 100px;
9
height: 100px;
10
border: 1px solid black;
11
border-radius: 10px;
12
background: lightgray;
13
}
14
15
.red-div {
16
background: red;
17
}
18
</style>
19
</head>
20
<body>
21
<div id="my-div" class="red-div"></div>
22
<button onclick="removeClass()">remove class attribute</button>
23
<script>
24
var myDiv = document.querySelector('#my-div');
25
26
function removeClass() {
27
myDiv.removeAttribute('class');
28
}
29
</script>
30
</body>
31
</html>