Reputation: 21
I want to change sub element of below data attribute
<div class="blue-shape"
data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>
for this i have added below jquery code but it doesn't work
$(document).ready(function(){
jQuery('.blue-shape').attr("data-actions",{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''});
});
.blue-shape
is div class name where i want to change data attribute
Upvotes: 1
Views: 359
Reputation: 74738
You can pass a function as a second arguement and you can iterate over to change any value like:
jQuery(document).ready(function($) {
console.log($('.blue-shape').data('actions'));
$('.blue-shape').attr("data-actions", function() {
var arr = $(this).data('actions'), newArr = [];
$.each(arr, function(i, obj){
if(obj.slide === "rs-18"){
obj.slide = "rs-16"
}
if(i === arr.length-1){ newArr.push(obj); }
});
return newArr;
});
console.log($('.blue-shape').data('actions'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-shape" data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'></div>
Upvotes: 2
Reputation: 380
I just updated your jquery with this following code please check and vote if it works
$('document').ready(function(){
jQuery('.blue-shape').attr("data-actions","[{'event':'mouseenter', 'action':'jumptoslide', 'slide':'rs-16','delay':''}]");
});
For Reference
https://jsfiddle.net/jasonantho/6ehmded3/
Upvotes: 0
Reputation: 73906
You need to pass string in 2nd param or you can simply use data()
method too like:
console.log($('.blue-shape').data("actions"));
$('.blue-shape').data("actions","[{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''}]");
console.log($('.blue-shape').data("actions"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="blue-shape"
data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>
Upvotes: 0
Reputation: 6145
jQuery.attr()
expects second parameter to be string.
have a look at jQuery.data()
also
$('document').ready(function() {
jQuery('.blue-shape')
.attr("data-actions", "{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''}");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue-shape" data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>DATA</div>
Upvotes: 0