Home arrow HTML arrow Page 2 - Deleting Data with the removeItem() Method in HTML5
HTML

Deleting Data with the removeItem() Method in HTML5


In this fifth part of the series, I show you how easy it is to remove data from the browser’s local storage by using the “removeItem()” method. As you'll soon see, the removal process practically speaks for itself, so you shouldn’t have major problems replicating it during the development of your own JavaScript applications.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
January 18, 2011
TABLE OF CONTENTS:
  1. · Deleting Data with the removeItem() Method in HTML5
  2. · Deleting data from the local storage with the removeItem() method

print this article
SEARCH DEVARTICLES

Deleting Data with the removeItem() Method in HTML5 - Deleting data from the local storage with the removeItem() method
(Page 2 of 2 )

If you found it easy to save and get data from the local storage using the “setItem()” and “getItem()” methods, then when I show you how to delete a specified item, you’ll feel even more pleased. Don’t believe me? Well, take a peek at the redefined version of the “HTML5Storage()” function, which now removes some existing items through the “removeItem()” method:

function HTML5Storage() {
    // add the items to the local storage
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
    // remove some items from the local storage
    localStorage.removeItem('lname');
    localStorage.removeItem('email');
    alert('The number of items saved to the local storage is: ' + localStorage.length);
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}

I don’t want to sound like I’m overreacting, but if you look closely at the above function, you’ll see that a couple of interesting things are happening there. First off, the function begins by saving some items in the local storage, which is a familiar process. This is done simply for demonstrative purposes, as some of these items are deleted later on via the “removeItem()” method.

Finally, the function pops out an alert box displaying the number of items that still remain in storage. This is accomplished with another property of the “localStorage” object, called “length.” That’s pretty easy to follow, isn’t it?

In theory, if three items were saved and then two of them were deleted, the value displayed by the alert should be 1, right? (Yes, my math skills are simply awesome). This isn’t mandatory, but to find out if this is true, the previous function should be attached to an HTML5 document.

That’s precisely what I plan to do below, so read the next few lines.

Setting up a functional example: adding the previous JavaScript function to a web page

By far, the best way to understand how the previous “removeItem()” does its thing is by example. Therefore, below I coded one for you, which includes the amended version of the “HTML5Storage()” function. Check it out:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 local Storage</title>
<script type="text/javascript">
// using the removeItem() method
function HTML5Storage() {
    // add the items to the local storage
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
    // remove some items from the local storage
    localStorage.removeItem('lname');
    localStorage.removeItem('email');
    alert('The number of items saved to the local storage is: ' + localStorage.length);
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #ccc;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
p {
    margin: 0 0 10px 0;
}
#wrapper {
    width: 960px;
    margin: 0 auto;
    background: #fff;
}
#header, #content, #footer {
    padding: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <header>
            <h1>HTML5 Storage</h1>
            <section>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
            </section>
        </header>
    </div>
    <div id="content">
        <h2>This is the main content section</h2>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
    </div>
    <div id="footer">
        <footer>
            <h2>This is the footer</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </footer>
    </div>
</div>
</body>
</html>

There you have it. At this time, you have at your disposal a concrete example that can be used for seeing the actual functionality offered by the “removeItem()” method, and by the “length” property as well. So, what are you waiting for? Go ahead and give the above web page a try.

If everything works as expected, the alert box should inform you that the number of items still present in the local storage is effectively 1. Of course, there’s plenty of room to experiment here, so I suggest you  alter the definition of the “HTML5Storage()” function and see what result you get in each case. It’ll be a pretty instructive experience, take my word for it. 
 
Final thoughts

In this fifth installment of the series, I provided you with another hands-on example, which demonstrated how easy it is to remove data from the browser’s local storage by using the “removeItem()” method. As you saw before, the removal process practically speaks for itself, meaning that you shouldn’t have major problems replicating it during the development of your own JavaScript applications.

So far, I've explained how to save, fetch and delete stored items through a set of specific methods or even by accessing the properties of the “localStorage” object, which has been a no-brainer process. But what happens if you need to delete all of the stored items in one go? In a case like this, using the “removeItem()” would be a painful, inefficient approach. So, is there a way to do it any better?

Again, the object’s API comes to the rescue. It provides a method called “clear(),” which can be used for flushing the local storage from top to bottom. Give that, in the coming tutorial I’ll be discussing how to use this additional method, as always, from a practical standpoint.

Don’t miss the next part!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials