我有多个要在HTML代码中编写的localstorage值。
我的主要div
名称是data
,并且h2
中有一个div
标记
<div id="data">
<h2></h2>
</div>
现在,如果我想将
localStorage
的值写入data
div,我会这样做, document.getElementById("data").innerHtml = localStorage.score;
但我想将其写在
h2
标记内,所以我在搜索Stackoverflow之后尝试了这个,
document.getElementById("data").getElementsByTagName('h2').innerText = localStorage.score;
和这个,
document.getElementById("data").getElementsByTagName('h2').firstChild.nodeValue = localStorage.score;
但是这两个都不起作用。
为什么有人不告诉我,它不起作用?
最佳答案
首先,为了获得第一个元素,请不要使用firstChild
,而应使用零索引
document.getElementsByTagName('h2')[0]
见How to get a html element by name
firstChild
用于嵌套子级,而不是元素数组。其次,像对待“内容”一样使用
innerHTML
document.getElementsByTagName('h2')[0].innerHTML = localStorage.score;
看到这个fiddle
关于javascript - 在div元素的h2标签内写入本地存储值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29819075/