JavaScript DOM Scripting By Example Improving the Application Code Next Steps

Marcus Schumacher
Marcus Schumacher
8,314 Points

[SOLVED] Slight Problem With Local Storage Challenge

I am so close!

function getStoredListItems() {
  var storedItems = localStorage.getItem('storedItems'); 
  if(storedItems) {
    return JSON.parse(storedItems);
  }
  else {
   return []; 
  }
}

function addStoredItem(str) {
  var storedItems = getStoredListItems();
  storedItems.push(str);
  localStorage.setItem('storedItems', JSON.stringify(storedItems));
}

Those functions seem to work. I successfully add each new List Item text value to storedItems in localStorage. This is exactly what storedItems under localStorage looks like: storedItems: "["Name","AnotherName","YetAnotherName"]"

Here is where the problem is

getStoredListItems().forEach(function(text) {
    createLi(text);
});

Nothing happens! No ListItems are created from the text I am given! Please help! For reference, here is the whole dang createLi function:

// This whole function creates a list item with all the required buttons and elements
function createLi(text){

   function createElement(elementName, property, value) {
      const element = document.createElement(elementName);
      element[property] = value;
      return element;
   }
   function appendToLi(elementName, property, value) {
     const element = createElement(elementName, property, value);
     li.appendChild(element);
     return element;
   }

   const li = document.createElement('li');

   appendToLi('span', 'textContent', text);

   appendToLi('label', 'textContent', 'Confirm')
    .appendChild(createElement('input', 'type', 'checkbox'));

   appendToLi('textarea', 'textContent', 'Notes'); // I need to make the display value of this text area block inline

   appendToLi('button', 'textContent', 'edit');

   appendToLi('button', 'textContent', 'remove');


   return li;
}

Are the items I am getting back from getStoredListItems not strings?

1 Answer

Steven Parker
Steven Parker
120,039 Points

You say "No ListItems are created from the text I am given!", but maybe they are.

The "createLi" function appears to create new list item elements and return them, but when you call it from within the "forEach", nothing is done with the return value. In particular, it's not being added to the DOM. So essentially the created element just exists in "limbo".

I would expect that you'd want to append them to an existing list (ul or ol).

Marcus Schumacher
Marcus Schumacher
8,314 Points

Thank you so much! I can't believe I didn't see that :D

Steven Parker
Steven Parker
120,039 Points

Marcus Schumacher — you can mark a question resolved by choosing a "best answer". Changing the title is a good option when you resolve an issue yourself but no-one has answered (or not in a way that was helpful.

Glad I could help, and happy coding!