简体   繁体   中英

localStorage is saving html as [object HTMLDivElement]

I want to save some html into localStorage

<div class='table'>
  <p>text</p>
</div>

Here's what I tried:

var table = document.getElementsByClassName('table')[0]
localStorage.setItem("mykey", table)
console.log(localStorage)

https://jsfiddle.net/gdv60aoL/

what I'm getting is: Storage {mykey: "[object HTMLDivElement]", length: 1}

What's [object HTMLDivElement]? Is this empty? I just want to store this as html.

Thank you in advance.

It is not empty, when you are logging, you are saying console.log(localStorage) , if you would to see the real value, do console.log(localStorage.getItem("mykey")) .

Also remember, localStorage only takes in string values, so you could do JSON.stringify , to convert it to a string.

Your variable is not a value, it's html element, use below example to do it.

var tableValue = document.getElementsByClassName('table')[0].value;
localStorage.setItem("myKey", tableValue);

You are almost there. If you want the complete block add outerHTML to the line that fetches the content. Everything else works.

var table = document.getElementsByClassName('table')[0].outerHTML
localStorage.setItem("mykey", table)

console.log(localStorage)

The outpus is as expected:

mykey: "<div class="table"><p>text</p></div>"

If you want only the paragraph element, then use .innerHTML .

The thing you save in localStorage is parsing of a HTML Object. Here you need to parse HTML Object into string and save it in to localStorage because localStorage stores data only in "key":"string" format (it means value must be in string data type)

To use HTML object as string:

var tableContent = table.outerHTML;
localStorage.setItem('myKey', tableContent);

Reference: outerHTML

It's showing up as '[object HTMLDivElement]' because you haven't serialized the object before storing it. Keep in mind that LocalStorage only stores string key-value pairs so whatever you store must be a string.

If what you were expecting is the html of the element, try:

var table = document.getElementsByClassName('table')[0]
localStorage.setItem("mykey", table.outerHTML)
console.log(localStorage)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM