Skitty
Skitty

Reputation: 1

Delete string in localStorage

I'm using local storage to display a list of things and I am just appending on to the end of the localStorage item. How would I delete a certain string from localStorage? They are all in a fib class with a unique id, it would also work if I could just remove the HTML from in between the divs but I don't know how I would actually execute it inside the localStorage item...

Upvotes: 0

Views: 61

Answers (2)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22935

You can use a list of strings and save it in localStorage but you first need to stringify it and parse it back on retrieval. You can create helper functions to save your code/time.

function setItem(key, obj){
   localStorage.setItem(key, JSON.stringify(obj));
}

function getItem(key){
   return JSON.parse(localStorage.getItem(key));
}

var data = [];
data.push('a');  // ['a']

setItem('data', data);

data = getItem('data'); // ['a']

data.push('b');  // ['a', 'b']

setItem('data', data);

data = getItem('data'); // ['a', 'b']

data.splice(data.indexOf('a'), 1); // ['b']

setItem('data', data);

data = getItem('data'); // ['b']


console.log(data); // ['b']

Upvotes: -1

Sean Vieira
Sean Vieira

Reputation: 160073

Since it's actually HTML, simply turn it back into HTML using createDocumentFragment:

var yourHTML = getItFromLocalStorage();

var fragment = document.createDocumentFragment();
fragment.appendChild(document.createElement('div'));
fragment.firstChild.innerHTML = yourHTML;
var yourElement = fragment.getElementById('your_id');
yourElement.parentNode.removeChild(yourElement);
// fragment.firstChild now contains your HTML *without* the
// element with your_id

Upvotes: 2

Related Questions