TIL prepend
POSTED ON:
When you're creating new elements in Javascript, you want to attach the new element to something that exists in the DOM already.
The most common method is append
.
<script>
document.body.append(document.createElement('p'));
</script>
<body>
<h1>Hello there</h1>
<p></p> <!-- new element created by JS -->
</body>
What if you want it BEFORE the h1?
You'll use prepend
, which attaches it as the first child.
<script>
document.body.prepend(document.createElement('p'));
</script>
<body>
<p></p> <!-- new element created by JS -->
<h1>Hello there</h1>
</body>
Via MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/prepend
Related TILs
Tagged: html