localStorage.removeItem not working when passing id from jquery

Im playing with HTML5 LocalStorage and it seems pretty straight forward for the most part.

Load the page with the following to insert the test values.

localStorage.setItem("artist-0", "0"); //saves to the database, key/value
		localStorage.setItem("artist-1", "1");
		localStorage.setItem("artist-2", "2");
		localStorage.setItem("artist-3", "3");

I then generate a list from the stored data.

var hideartist = '';
			for (var i = 0; i < localStorage.length; i++){
				hideartist += "<li id=\\"artist-" + localStorage.getItem("artist-"+i) + " \\">" + localStorage.getItem("artist-"+i) + "</li>";
				
				}
			//alert(hideartist); // show hideartist
  			$('#artisthidelist').append(hideartist); // add top artists

However, when I try and remove a value using a key that’s generated by grabbing the id atribute of an element from jquery it just seems to fail.

Im struggling with is below. I can see from the alert that the ‘key’ seems to be Ok.

$("#artisthidelist li").live("click", function () {
			var deletenum = '';
			
			var deletenum = $(this).attr("id")
			alert(deletenum);
			localStorage.removeItem(deletenum);
		});

Any ideas what Im doing wrong? I’ve set up a test page here

It looks like you are trying to remove an item based on it’s value not the index?

Perhaps try this:


var hideartist = '';
			for (var i = 0; i < localStorage.length; i++){
				hideartist += "<li id=\\"artist-" + i + " \\">" + localStorage.getItem("artist-"+i) + "</li>";

				}
			//alert(hideartist); // show hideartist
  			$('#artisthidelist').append(hideartist); // add top artists

Thanks Anthony - Maybe I’m misunderstanding you, but that code is for listing the items in local storage as <li> elements and is working Ok.

It is the removing I am having problems with.

// works


		var deletenum = 'artist-2';
		localStorage.removeItem(deletenum);

// works

var deletenum = '3';
		localStorage.removeItem("artist-"+deletenum);

// doesn’t work

$("#artisthidelist li").live("click", function () {
			var deletenum = '';
			var deletenum = $(this).attr("id")
			localStorage.removeItem(deletenum);
		});

In your id attribute you have a space after the number which would cause an incorrect value to be passed into the removeItem method.

Thanks Sgt! Wood for trees.