0

I'm having trouble creating a new div for each object in the local storage array of objects. I have a form that's input values are added as objects into local storage, which holds an array of all the objects created from the form. Currently, it is only pulling the last object in the array and changing the div every time a new object is added.

Here is the code I have:

const localStorageData = localStorage.getItem('Form Values');
const localStorageParsed = JSON.parse(localStorageData)
console.log(localStorageParsed) // returns array of objects from local storage. 

// Creating each element to go into the div that will appear on the page. 
const blogDiv = document.createElement("div");
const h2El = document.createElement('h2');
const pEl = document.createElement('p');
const h6El = document.createElement('h6');

// adding classes to elements
blogDiv.classList.add('blog-post');
h6El.classList.add('posted-by');

// appending elements to div
blogDiv.appendChild(h2El);
blogDiv.appendChild(pEl);
blogDiv.appendChild(h6El);

// console.log(blogDiv);


// function to go through each object in the array from local storage

function addInputsToPost () {


for (let i = 0; i < localStorageParsed.length; i++) {
    h2El.textContent = localStorageParsed[i].title;
    pEl.textContent = localStorageParsed[i].content;
    h6El.textContent = localStorageParsed[i].username;
 
}


if (h2El.innerText == "" 
    && pEl.innerText == "" 
    && h6El.innerText == "") {
        !addInputsToPost();
    } else {
        // append new div to body
        document.body.appendChild(blogDiv);
       
    }

}

// call function
addInputsToPost();

0

Browse other questions tagged or ask your own question.