EN
JavaScript - remove element from DOM
5 points
In this artcle, we would like to show how to remove some Element or Node from DOM using JavaScript.
Quick solution:
xxxxxxxxxx
1
var element = document.querySelector('#element');
2
3
element.remove();
Hint: element
remove()
method was introduced in the major web browsers around 2013-2015.
In this section you can find different methods that let's to remove Node from DOM. In DOM Nodes are: Element, Text, Comment. For more details check out this article.
This approach works in older web browsers.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element">Some text here ...</div>
5
<button onclick="removeText()">Remove text</button>
6
<script>
7
8
function removeNode(element) {
9
var parent = element.parentNode;
10
if (parent) {
11
parent.removeChild(element);
12
}
13
}
14
15
16
// Usage example:
17
18
var element = document.querySelector('#element');
19
20
function removeText() {
21
removeNode(element);
22
}
23
24
</script>
25
</body>
26
</html>
This approach is not supported by older web browsers (before 2013-2015).
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element">Some text here ...</div>
5
<button onclick="removeText()">Remove text</button>
6
<script>
7
8
var element = document.querySelector('#element');
9
10
function removeText() {
11
element.remove();
12
}
13
14
</script>
15
</body>
16
</html>