EN
JavaScript - custom prependChild method
3
points
In this article, we would like to show you how to create a custom prependChild()
method in JavaScript.
Note:
In JavaScript, there's a prepend method, but in this example, we show a custom implementation of a method that appends a child at the beginning of a container element.
Quick solution:
function prependChild(parent, child) {
var placeholder = parent.firstChild;
if (placeholder) {
parent.insertBefore(child, placeholder);
else {
parent.appendChild(child);
}
}
Practical example
In this example, we create prependChild()
function that appends child
element at the beginning of a parent
element. To do so, the method is checking firstChild
property and uses insertBefore()
and appendChild()
methods.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
</div>
<script>
function prependChild(parent, child) {
var placeholder = parent.firstChild;
if (placeholder) {
parent.insertBefore(child, placeholder);
} else {
parent.appendChild(child);
}
}
var container = document.querySelector('#container');
var element = document.createElement('div');
element.textContent = 'New element';
prependChild(container, element);
</script>
</body>
</html>