1

I am trying to append a javascript variable within one of my html tags however it does not work at all even though the variable has a value. I am grabbing the variable through local storage so I am not sure if it is because of that or not? Any help would be greatly appreciated!

<div id="wrapper">
  <!-- Sidebar -->
  <div id="sidebar-wrapper">
    <ul class="sidebar-nav">
      <li class="sidebar-brand">
        <h3 id="welcome"></h3>=
        <script>
          var name = localStorage.getItem('name')
          document.getElementById("welcome").value = name;
        </script>
      </li>
      <li>
        <a href="#">Dashboard</a>
      </li>
      <li>
        <a href="#">Shortcuts</a>
      </li>
      <li>
        <a href="#">Overview</a>
      </li>
      <li>
        <a href="#">Events</a>
      </li>
      <li>
        <a href="#">About</a>
      </li>
      <li>
        <a href="#">Services</a>
      </li>
      <li>
        <a href="#">Contact</a>
      </li>
    </ul>
  </div>
</div>
MTCoster
  • 5,868
  • 3
  • 28
  • 49
GrandeurH
  • 147
  • 1
  • 1
  • 13
  • You open a P tag and you close a h3 tag, this looks like a typo – R Pelzer Dec 06 '18 at 11:56
  • Apologies, supposed to be a h3 tag – GrandeurH Dec 06 '18 at 11:57
  • How is this value being stored in the localStorage? – Calvin Nunes Dec 06 '18 at 11:58
  • Here you can find iformation how to view or edit your local storage: https://stackoverflow.com/questions/9404813/how-to-view-or-edit-localstorage – R Pelzer Dec 06 '18 at 11:59
  • @CalvinNunes The problem exists even without the call to `localStorage` – MTCoster Dec 06 '18 at 11:59
  • The variable does have a value as i console out it, setting it like this for now : localStorage.setItem('name', "John"); – GrandeurH Dec 06 '18 at 11:59
  • but you are not setting it, you are just getting it... `localStorage.getItem("name")` tries to find a "variable" stored under name of "name" and returns it string value. If you never use `localStoage.setItem("name", "some value")` it will never exist – Calvin Nunes Dec 06 '18 at 12:01
  • I am setting it in another html page, the problem isnt that the variable does not exist as I am able to see the variable – GrandeurH Dec 06 '18 at 12:02
  • 1
    so use `.textContent = name` or `.innerHTML = name`... not `.value = name`. `value` are just for input like elements – Calvin Nunes Dec 06 '18 at 12:03
  • Yup that was the issue, I got confused between innerHtml and value, totally forgot value is just for inputs! – GrandeurH Dec 06 '18 at 12:06

2 Answers2

0

if the name variable is definitely set use .innerHTML instead of .value

Paddy Hallihan
  • 1,624
  • 3
  • 27
  • 76
0

Try innerHTML

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

<script>
var name = localStorage.getItem('name')
document.getElementById("welcome").innerHTML= name;
</script>
codemirror
  • 3,164
  • 29
  • 42