skip to Main Content

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


  1. You need to specify the element to add blogPostData.
    Please try this document.getElementById("your other id").appendChild(blogPostDiv);

    Login or Signup to reply.
  2. If you are talking about the element <main>, you need to get it from the document (DOM) before you can append anything to it:

    const mainElement = document.querySelector('main') // Or document.getElementsByTagName('main')[0]
    mainElement.appendChild(blogPostDiv); 
    

    main is not a valid (default) property of document obj

    Docs:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search