admin管理员组

文章数量:1306776

I need to save contents of a html div (id=tabela) to localstorage, so that the contents of the table can be loaded in another session via localstorage. How to get the div contents into a variable?

var = tabelaContent; //<-- I need contents of <div id=tabela> in this 
localStorage.setItem("tabelaContent",tabelaContent);

// then, upon pressing the "load" button

localStorage.getItem(tabelaContent);

FYI if there is another way of making the table's content persistent, let me know

TIA.

I need to save contents of a html div (id=tabela) to localstorage, so that the contents of the table can be loaded in another session via localstorage. How to get the div contents into a variable?

var = tabelaContent; //<-- I need contents of <div id=tabela> in this 
localStorage.setItem("tabelaContent",tabelaContent);

// then, upon pressing the "load" button

localStorage.getItem(tabelaContent);

FYI if there is another way of making the table's content persistent, let me know

TIA.

Share Improve this question asked May 9, 2016 at 18:35 Stan KenwayStan Kenway 951 gold badge2 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You can use document.getElementById("myID").innerHTML, like this:

var = tabelaContent; 

tabelaContent = document.getElementById("tabela").innerHTML
localStorage.setItem("tabelaContent",tabelaContent);

Here is what you are looking for.

<div id="tabela">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea modo consequat. 
</div>

<button id="del" onclick="destroy()">Destroy div Content</button>
<button id="res" onclick="retrieve()">Restore content  from local storage</button>

<script>

  var tabelaContent = document.getElementById("tabela").innerHTML;

    // Store Content
    localStorage.setItem("tabelaContent", tabelaContent);

function destroy(){
    document.getElementById("tabela").innerHTML = "";
}

    // Retrieve Content    
function retrieve(){
    document.getElementById("tabela").innerHTML = localStorage.getItem("tabelaContent");
}


</script>

Check this working demo

本文标签: javascriptSave a part of html to local storage later loadStack Overflow