Use setItem
and getItem
if you want to write simple strings to localStorage. Also you should be using text()
if it's the text you're after as you say, else you will get the full HTML as a string.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// alert the value to check if we got it
alert(localStorage.getItem('test'));
JSFiddle: https://jsfiddle.net/f3zLa3zc/
// get html
var html = $('#test')[0].outerHTML;
// set localstorage
localStorage.setItem('htmltest', html);
// test if it works
alert(localStorage.getItem('htmltest'));
JSFiddle:
https://jsfiddle.net/psfL82q3/1/
A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable
and blur()
is used to change the contents of the div and overwrite the old localStorage
entry.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// bind text to 'blur' event for div
$('#test').on('blur', function() {
// check the new text
var newText = $(this).text();
// overwrite the old text
localStorage.setItem('test', newText);
// test if it works
alert(localStorage.getItem('test'));
});
If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.
JSFiddle:
https://jsfiddle.net/g1b8m1fc/