0

I tried to find an answer to this, but there are too many variables at play, so I hope some of you could explain to me what is happening here. I have a basic HTML page with a div which has "issuesList" id.

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body onload="foo();">
       <div id="issuesList"></div>
       <script src="main.js"></script>
    </body>
</html>

This is my main.js:

function foo(){
    //var issues = JSON.parse(localStorge.getItem('issues'));
    var issuesList = document.getElementById('issuesList');
    document.getElementById('issuesList').setAttribute("style", "color:red;")
    issuesList.setAttribute("style", "color:red;");
    issuesList.innerHTML = 'XYZ';
}

The localStorage is empty, so it has no 'issues' object.

If I leave the commented line commented out, the issuesList DOM element will show XYZ written in red. If I uncomment it, then issuesList element remains empty. I don't understand why this is happening.

Also, if I add 'issues' to localStorage, and call again foo() method, still nothing is shown in the 'issuesList' element.

Thank you

2
  • 3
    What does your console look like when you leave the JSON parse line uncommented? any errors? My guess is JSON.parse is failing, and so the rest of your code isn't executing. Commented Sep 5, 2017 at 19:40
  • 1
    An error will effectively stop JS in its tracks. If you're trying to parse undefined, that will do. Commented Sep 5, 2017 at 19:41

1 Answer 1

1

Here's the code, fixed:

function foo(){
    var issues = JSON.parse(localStorage.getItem('issues') || "[]");
    var issuesList = document.getElementById('issuesList');
    issuesList.style.color = "red";
    issuesList.innerHTML = 'XYZ';
}

This will set issues to an empty array if there's nothing in localStorage. I also removed the superfluous line in the middle. (You also had a typo: localStorge; always check your browser console)

Edit: it actually seems to mostly boil down to the typo. If the item isn't in localStorage, trying to get it returns null, and parsing that as JSON also returns null.

Additional note: localStorage can store objects; there's no need to stringify when storing and thus shouldn't be a need to parse when loading.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.