How to create new HTML elements with JS

To be able to create new elements, we say:

document.createElement. And we can create elements with any tag we like. For example, a div:

const newPost = document.createElement("div");

This is created as object, so we can modify it's properties, for example, it's class. Maybe give it the class 'top-post'. If it's an important post. Or change the HTML within it, give it some strong text:

newPost.innerHTML = "<strong>This is a new post!</strong>";

If we wanted to add an element to the document body, what would we do? We could just say:


Conversely, we can put it in the opposite place with prepend:


Let's say we wanted to put it at the beginning of the post list however, at the top of the page. How would we do that?

We would first need to query for the element next to where we wanted to place the post. Since it's above the first post, we would have to query for the first post:

const post = document.querySelector(".post");

And we see it's up there at the top.