1

I've got a script in good working order that checks to see if a visitor has been assigned a coupon code but wanted to add functionality that retrieves the coupon code that they were assigned and displays it. Both rely on the localStorage property. The problem I'm running into is that when I display the stored value, it's returning [object HTMLSpanElement] instead of the value that should be assigned.

Pretty much everything I've found on the issue is due to scope, but I don't see how I have a scope issue...even tried making the variables global in scope and that didn't seem to do anything.

Here is the JS:

if(localStorage.getItem("visited") != "true"){
    localStorage.setItem("visited","true"); 
    var codeValue = document.getElementById("code");
    localStorage.setItem("code",codeValue);
} 
else { 
    var savedCode = localStorage.getItem("code");
    document.getElementById("message").innerHTML = "You've already been assigned coupon code " + savedCode;
}

Here is the relevant HTML:

<span id="message">Your coupon code is: <span id="code">CODE1234</span></span>

When you return to the page after already visiting it, I expect the span text to display You've already been assigned coupon code CODE1234, but instead it is returning You've already been assigned coupon code [object HTMLSpanElement]

Note that part of the script was something I had created before and put in production, and I'm basically piggybacking off of that functionality. Previously, if getItem("visited") != "true" returned false, it popped up an alert box and said you'd already been given a code, then redirected you to another page.

Mamun
  • 66,969
  • 9
  • 47
  • 59
adrysdale
  • 47
  • 1
  • 10
  • 1
    `var codeValue = document.getElementById("code");` – that’s not a value, it’s an element. – Ry- Apr 10 '19 at 13:58
  • `document.getElementById("code")` returns an `HTMLSpanElement`. If you want the text, get the `textContent`. If you want its HTML, use `innerHTML`. – Heretic Monkey Apr 10 '19 at 13:59
  • Probably a dupe of [javascript getElementById and convert it to String](https://stackoverflow.com/q/2470089/215552) – Heretic Monkey Apr 10 '19 at 14:06

2 Answers2

5

You are storing the element itself (which is an object) in the localStorage. You should store the text of the element.

Change

var codeValue = document.getElementById("code");

To

var codeValue = document.getElementById("code").textContent;

Please Note: According to Window.localStorage

The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).

Mamun
  • 66,969
  • 9
  • 47
  • 59
0

you need to access the text inside the element, here you are storing the html element inside the localstorage. change the code to access the text

document.getElementById('code').innerText
Joseph
  • 682
  • 5
  • 17