Delete all dynamic attribute data for an item

I have a div where dynamic data attributes are added to some tags. (the name of the data attributes that will be generated dynamically using the script, so my script will not know the NAME attribute of the data attribute)

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

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

I can use

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

but the problem is that I do not know the name of the data attribute to be added. the data attribute to be added is dynamic and I do not control it.

deleting a div and re-nesting a div is not an option. Help Pls. thanks in advance

+4
source share
3 answers

You can use like that

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

Offered by @Mottie

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

Demo

+7
source

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);
}

$('div').data();prepare a list of all data attributes in the variable var data. Then you can work with him. This is the script for this solution .

UPDATE Posted by @Mottie

 $.each($('div').data(), function (i) {
        //for change 
        $('div').attr("data-"+i,"something");
        //for remove
        $("div").removeAttr("data-" + i);
    });
+2
source

, removeData() - , . data, .

.removeData() , .data(). ,.removeData() ; , . jQuery.data() HTML5 ; .removeAttr(), .

. , . , data() ( removeData).

data() key => value, removeAttr().

0
source

Source: https://habr.com/ru/post/1543401/


All Articles