How to change sub element of data attribute using jquery

355 Views Asked by At

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

4

There are 4 best solutions below

0
On

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>

0
On

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":""}]'>

4
On

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/

0
On

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>