Nah, both don't work, because you're not actually finding the correct index of your tag.
Why not? Because $(this).text()
includes the delete mark you added, ×
- e.g. "Morning×". Since that's not in your tags
array, index
will be -1. tags.splice(-1, 1);
will remove 1 item from the end of the array.
In general, it's never a good idea to use presentation text (i.e. the text of your tag element) as data (e.g. using that text as a lookup value in an array). It's very likely that it'll be broken when something changes in the presentation - like here. So a suggestion would be to store the data (what you need to look up the tags) as data - e.g. using the jQuery-provided data()
API - even if it seems redundant.
Here's a quick example - just adding/replacing two lines, which I've marked with comments starting with "JT": JSFiddle
Now, instead of looking up by $(this).text()
, we're looking up by the data value "tagValue" stored with $(this).data()
- that way, the lookup value is still bound to the element, but we're not relying on presentation text.