I used the following code that allows for creating a "blog post" that is composed of multiple divs. I want that every time I click the button a new blog post is created but what actually happens is that no new posts are created and the only thing that changes is the content of the divs, to be specific the content of contentDiv
. In other words, the user input or the post content is the only thing that changes.
const BtnAdd = document.getElementById("buttonpost1");
BtnAdd.addEventListener("click", AddNew);
function AddNew() {
var newhtml = document.getElementById("postbox").value;
sessionStorage.setItem("page1content", newhtml);
document.getElementById("postbox").value = "";
location.reload();
return false;
}
var newhtml2 = document.getElementById("profilecontent").innerHTML;
var newhtml3 = document.getElementById("underpost").innerHTML;
var newhtml4 = document.getElementById("commentcontent").innerHTML;
sessionStorage.setItem("usercontent" , newhtml2);
sessionStorage.setItem("belowcontent", newhtml3)
sessionStorage.setItem("commentcont", newhtml4)
const contentDiv = document.createElement("div");
const userDiv = document.createElement("div");
const lowerDiv = document.createElement("div");
const commentDiv = document.createElement("div");
const bigDiv = document.createElement("div");
bigDiv.classList.add("div-shadow");
contentDiv.classList.add("div-shadow2");
userDiv.classList.add("div-shadow3");
lowerDiv.classList.add("div-shadow4");
commentDiv.classList.add("div-shadow5");
userDiv.innerHTML = sessionStorage.getItem("usercontent");
contentDiv.innerHTML = sessionStorage.getItem("page1content");
lowerDiv.innerHTML = sessionStorage.getItem("belowcontent");
commentDiv.innerHTML = sessionStorage.getItem("commentcont");
var cWrapper = document.getElementById("contentwrapper");
bigDiv.appendChild(contentDiv);
bigDiv.appendChild(userDiv);
bigDiv.appendChild(lowerDiv);
bigDiv.appendChild(commentDiv);
cWrapper.appendChild(bigDiv);
what changes should I make to allow for the creation of a new blog post each time the user clicks the button of id buttonpost1
and not just override the content of the existing post (divs)?
I don't see any appendChild
in your AddNew
function, you need to create and append new elements each time the AddNew
function gets called.
This is a minimal example:
const container = document.querySelector('#container');
const button = document.querySelector('button');
button.addEventListener('click', () => {
addNewPost();
});
function addNewPost() {
const newPost = document.createElement('div');
newPost.innerText = 'New Post';
container.appendChild(newPost);
}
<button type="button">Add New Post</button>
<div id="container"></div>