Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all dynamic 'data attributes' of an Element [duplicate]

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

like image 877
Prashant Avatar asked Jun 05 '14 11:06

Prashant


3 Answers

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

like image 113
Anoop Joshi P Avatar answered Oct 17 '22 00:10

Anoop Joshi P


You can use this code :

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

for(var i in data){
    //for change 
    $('div').attr("data-"+i,"something");
    //for remove
    $("div").removeAttr("data-" + i);
}

The $('div').data(); prepare a list of all data attributes in var data variable. Then you can work with it. This is fiddle of this solution.

UPDATE Suggested by @Mottie

 $.each($('div').data(), function (i) {
        //for change 
        $('div').attr("data-"+i,"something");
        //for remove
        $("div").removeAttr("data-" + i);
    });
like image 28
Saman Gholami Avatar answered Oct 17 '22 00:10

Saman Gholami


I think that the removeData() function is what you are looking for here. This will remove all data information stored on the element.

The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not affect any HTML5 data- attributes in a document; use .removeAttr() to remove those.

It will not however remove the actual attributes from the elements. In order to remove the actual attributes, you'll need to extract a list of the existing attributes. You could do this by inspecting the data() function of an element (before running removeData).

The data() function will return an object of key => value pairs that you can then use to remove the actual attributes from the element using removeAttr().

like image 33
Lix Avatar answered Oct 16 '22 23:10

Lix