EN
JavaScript - replace child element
0 points
In this article, we would like to show you how to replace a child element using JavaScript.
Quick solution:
xxxxxxxxxx
1
parentNode.replaceChild(newChild, oldChild);
In this example, we present how to use replaceChild()
method to replace oldChild
of the parentNode
with a newChild
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">
5
<div id="child-element">Example text...</div>
6
</div>
7
<script>
8
9
// get handle to element to replace
10
var oldChild = document.querySelector('#child-element');
11
12
// create new element
13
var newChild = document.createElement('div');
14
newChild.textContent = 'new child text...';
15
16
// get handle to the parent node
17
var parentNode = oldChild.parentNode;
18
19
parentNode.replaceChild(newChild, oldChild);
20
21
</script>
22
</body>
23
</html>