Removing all dynamic 'data attributes' of an Element

Prashant picture Prashant · Jun 5, 2014 · Viewed 10.9k times · Source

I have a div where dynamic data- attributes get added on some tags. (name of data- attributes to be generated dynamically by script, so there is no way my script will know the NAME of data-attribute)

<div data-1223="some data" data-209329="some data" data-dog="some value"> </div>

Now, I want to write a code in which it resets the div by removing all the data attributes and their values.

I can use

$('div').attr('data-209329',"")

but the problem is I don't know the name of data-attribute that will be added. the data-attribute that will be added is dynamic and I don't have control of it.

removing div and reinserting div is not an option. Pls help. thanks in advance

Answer

Anoop Joshi picture Anoop Joshi · Jun 5, 2014

YOu can use like this

var data = $("div").data();

var keys = $.map(data, function (value, key) {
    return key;
});
for (i = 0; i < keys.length; i++) {
    $("div").removeAttr("data-" + keys[i]);
}

Fiddle

Edit

Suggested by @Mottie

$.each($('div').data(), function (i) {
    $("div").removeAttr("data-" + i);
});

Demo