EN
JavaScript - prepend element
3
points
In this article, we would like to show you how to prepend element using JavaScript.
Quick solution:
var parent = document.querySelector('#parent');
parent.prepend(document.createElement('div'));
Warning:
prepend()
method appeared around 2015 in major web browsers.
Practical examples
In the below, you can find two solutions that solves the problem.
1. Custom solution
In this section, you can find solution that works in older web brosers too.
// 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>
2. prepend()
methods
In this example, we use prepend()
method that appeared around 2015 in major web browsers.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
</div>
<script>
var container = document.querySelector('#container');
var element = document.createElement('div');
element.textContent = 'New element';
container.prepend(element);
</script>
</body>
</html>