EN
JavaScript - remove DOM element
4 points
In this article, we're going to have a look at how to dynamically remove DOM element in JavaScript.
Simple overview:
xxxxxxxxxx
1
// not supported by older browsers (not supported in all IE versions)
2
element.remove();
3
4
// works for older browsers too
5
element.parentNode.removeChild(element);
Note: it is good to check that parent node exists - element is placed in other element.
There are 2 simple ways how to do it:
- directly with
remove
method, - with
removeChild
method.
Look on the below code too see practical example.
Solution presented in this section remove element with one methof call (remove
method).
Note: not supported by older browsers (not supported in all IE versions)
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element">Element here...</div>
5
<script>
6
7
var element = document.querySelector('#element');
8
element.remove();
9
10
</script>
11
</body>
12
</html>
Solution presented in this section checks that parent element (for removed element) exists and remove the element from it.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element">Element here...</div>
5
<script>
6
7
function removeElement(element) {
8
var parent = element.parentNode;
9
if (parent == null) {
10
throw new Error('Element does not have parent.');
11
}
12
parent.removeChild(element);
13
}
14
15
var element = document.querySelector('#element');
16
removeElement(element );
17
18
</script>
19
</body>
20
</html>