1

this is my first question on stackoverflow. and a little bit experience on code.

so I have a localstorage like this:

myDB: "[{"key:"123","label":"abc"}]

I have a div with "abc" as value:

<div id="name">abc</div>

And many id's div clone with different value

<div id="name">abc</div>
<div id="name">cde</div>
<div id="name">efg</div>

I want to read the value of the ID "name", make a if/else like looking "abc" are in the localstorage, if yes delete it with the key. else not delete.

I have thinking of using document.getElement to get value from ID and compare it to localstorage and using if else to do that thing. But there are many clone have that event to trigger the function to delete it. So the function don't know which ID's value to be compare and delete it.

I really awkward for this newbie question. But I have to ask, many thanks first :)

*New question:

I want to delete last element of the localstorage. Can I convert localstorage to array then using array.pop(). Then convert the changed array again to the localstorage?

Trung
  • 11
  • 4
  • 1
    `id`s should be unique on the page; what you probably want to do is use `class` instead, then `getElementsByClassName` will give you an HTMLCollection of all your elements – Hamms Jun 14 '18 at 21:29
  • 1
    I agree with Hamms, your `div`s should have a unique id. Also, for managing local storage here are some good methods: `setItem()` Add key and value to local storage `getItem()` Retrieve a value by the key `removeItem()` Remove an item by key `clear()` Clear all storage – Esther Cuan Jun 14 '18 at 21:30

2 Answers2

1

First, as was mentioned by others, id must be unique. You can use any other attribute instead, for example, class:

<div class="name">abc</div>
<div class="name">def</div>
<div class="name">ghi</div>
<div class="name">jkl</div>
<div class="other">mno</div>

Then, to query these elements, you could use document.getElementsByClassName("name") which will return you an array-like object. You can convert this object to an array of values using a combination of spread syntax and map method:

let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);

To work with the local storage you can use localStorage.setItem and localStorage.getItem. As you know, the local storage stores only strings, so JSON.parse and JSON.stringify methods will be helpful too.

Here is the example of code:

localStorage.setItem("myDB", '[{"key":"123","label":"abc"}, {"key":"456","label":"mno"}]');
console.log('Local storage before: ', localStorage.getItem("myDB"));
// extracting div values to an array
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
// creating a js object from myDB string
let db = JSON.parse(localStorage.getItem("myDB"));
// leaving only those elements, which labels are not in the values array
localStorage.setItem("myDB", JSON.stringify(db.filter(item => !values.includes(item.label))));
console.log('Local storage after: ', localStorage.getItem("myDB"));

JSFiddle link: https://jsfiddle.net/v03wpgq1/4/

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
  • @JonP agreed. it's what id stands for – Kirill Simonov Jun 15 '18 at 04:59
  • @JonP - I mean, they really shouldn't. But that doesn't necessarily mean *must* be unique: http://jsfiddle.net/s91moxdu/ ... – Travis J Jun 15 '18 at 07:31
  • @TravisJ, nope, as per the spec it **must** be unique see: https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute & https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id – Jon P Jun 17 '18 at 23:34
  • @JonP - I mean, just to be pedantic, the definition of must is should. So, semantically, there was no difference between the two in your earlier comments. From a use standpoint though, there are situations where non unique identifiers can be used, as shown. They should be unique. They can also not be unique and still be used as valid identifiers to locate elements. Hopefully no one does that, but it is best to at least show all the information. – Travis J Jun 18 '18 at 06:54
  • @TravisJ, we've derailed this enough but, being pedantic, the definition of "must" is **not** "should" : https://blog.oxforddictionaries.com/2014/03/03/must-should-ought/. "Should" implies that there is an option, but a preference. With "must" there is no option, and this is what the spec states. – Jon P Jun 18 '18 at 07:36
  • @JonP - Google defines it as "be obliged to; should (expressing necessity)." But I understand where the author of the blog was coming from as well. While the spec may indicate uniqueness, that is not how the implementation works in all cases. Id's should be unique, there is the option for them to be used as non unique identifiers. It may be a bad option, but regardless, it exists. – Travis J Jun 18 '18 at 08:05
0
  • id attributes should be unique on the page, otherwise only the last one on the page has the ability to be referenced easily (or at least, properly).

  • There should be a section that contains these which makes them easily queryable. Perhaps inside of an element with an id guaranteed to uniquely hold a set of name value pairs.

  • Using document.querySelectorAll is your best bet for finding these elements, and will be made easier by creating a structure that can be queried.

  • With a set of items to look for, it should be easy to iterate and test for values and keys inside of localStorage.

Travis J
  • 81,153
  • 41
  • 202
  • 273