0

I have multiple localstorage values that I want to write in the HTML code.

My main div name is data and there is an h2 tag inside that div

<div id="data">
   <h2></h2>
</div>

Now if i want to write the value of my localStorage to the data div i would do this,

    document.getElementById("data").innerHtml = localStorage.score;

but I want to write it inside the h2 tag, So i tried this after searching on Stackoverflow,

    document.getElementById("data").getElementsByTagName('h2').innerText = localStorage.score;

and this,

document.getElementById("data").getElementsByTagName('h2').firstChild.nodeValue = localStorage.score;

but both of these are not working. Why it is not working can anybody tell me ?

Riley Willow
  • 594
  • 2
  • 5
  • 21
  • The method getElementsByTagName() returns an array, it accesses all elements with the specified tagname. Use getElementsByTagName('h2')[0] to add value to it. Like document.getElementsByTagName('h2')[0].innerHTML = localStorage.score; – Kurenai Kunai Apr 23 '15 at 09:44

3 Answers3

2

First, in order to get the first element, do not use firstChild, rather, use the zero index instead

document.getElementsByTagName('h2')[0]

See How to get a html element by name

firstChild is for nested children, not an array of elements.

Second, use innerHTML like you were for 'content'

document.getElementsByTagName('h2')[0].innerHTML = localStorage.score;

See this fiddle

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0

Based on the code you posted you need to either change the div id from data to content or change call the getElementById with the "data" parameter.

That is, if there is indeed something in localStorage.score to show.

Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
0

The method getElementsByTagName() returns an array, it accesses all elements with the specified tagname. Use getElementsByTagName('h2')[0] to add value to it.

Like

document.getElementsByTagName('h2')[0].innerHTML = localStorage.score;

Kurenai Kunai
  • 1,842
  • 2
  • 12
  • 22