Today I Learned - Rocky Kev

TIL prepend

POSTED ON:

TAGS:

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:

TIL Gmail has a 102KB size-limit for HTML

PLACEHOLDER

TIL how Error correction works in HTML

You never get an 'Invalid Syntax' error on an HTML page. Browsers fix any invalid content and go on.

TIL what DOCTYPE means

tl;dr: DOCTYPE declaration in the first line of the HTML file, to instruct the browser to run the code in Standard mode.