trying to create a div element after form is submitted to store input on next page
must be able to create a new div for every post and render them, it only works when appended to body, i need it in the main
i’ve tried multiple google fixes and asked a friend who codes in typescript
document.addEventListener('DOMContentLoaded', function() {
var formData = JSON.parse(localStorage.getItem('formData'));
if (formData) {
var blogPostDiv = document.createElement('div');
blogPostDiv.classList.add('blog-post');
var usernamePara = document.createElement('p');
usernamePara.textContent = 'Author: ' + formData.username;
var titlePara = document.createElement('h2');
titlePara.textContent = formData.title;
var contentPara = document.createElement('p');
contentPara.textContent = formData.content;
blogPostDiv.appendChild(usernamePara);
blogPostDiv.appendChild(titlePara);
blogPostDiv.appendChild(contentPara);
// Append the div to the body or another desired location
document.main.appendChild(blogPostDiv);
} else {
// Handle case where data is not found in localStorage
console.log('No blog post data found.');
}
});
2
Answers
You need to specify the element to add blogPostData.
Please try this document.getElementById("your other id").appendChild(blogPostDiv);
If you are talking about the element
<main>
, you need to get it from the document (DOM) before you can append anything to it:main
is not a valid (default) property of document objDocs: