Question

Given this markup:

<a data-foo="bar baz">Hello</a>

Is it possible to remove baz but keep bar, ideally without removing both then adding back bar.

The jQuery removeData method appears to remove the specified data attribute or all data attributes.

Was it helpful?

Solution

You can do

 $('a').data('foo', $('a').data('foo').split(' ')[0])

OTHER TIPS

I'm not really sure this is what you're looking for, but this may help

  1. First get the data-foo values

    var foo = $('a').data('foo')

  2. Split the foo string to an array

    var foos = []

    foos = foo.split(" ")

  3. Pick the items you want to keep (or remove the items you want to remove)

    var index = foos.indexOf("baz")

    foos.splice(index,1)

  4. Put the string back together with only the left foos

    var foo = foos.join(" ")

  5. Set the data-foo to the new filtered one

    $('a').data('foo',foo)

Assuming data is a space delimited string:

var data = $("a").data("foo");
data = (" " + data + " ").replace(" baz ", " ").replace(/^ | $/g, "");
$("a").data("foo", data);

This should work for foo baz, baz foo, foo baz bar, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top