javascriptjqueryjquery-countdown

How to add a new data in data attribute


I have countdown made with handlebars which is added to the data attribute of my element but what I wanted is to add the current year. The framework countdown that Im using is the final countdown which accepts this data-countdown format of "2017/06/14" my html is this:

<div class="cd" id="cd" data-countdown="{{month}}/{{day}} {{time}}"></div>

What I wanted to achieve is to add the year in the first index as

data-countdown="2017/{{month}}/{{day}} {{time}}"

This is my js script so far:

var currentDate = new Date().getFullYear();

$('.cd').each(function(){
  //get each data-attribute
  var a = $(this).data("countdown");
  var b = a.split(" ");
  //add the current year to it
  b.unshift(currentDate);
  c = b[0]+'\/'+b[1]+'\/'+b[2];
  $(this).data("countdown", c); });

Solution

  • Just prepend the current year to the already existing data.

    $('.cd').each(function(){
      var getDataCountDown = $(this).data("countdown");
      var getYear = new Date().getFullYear(); // or whatever the year you want
      var newData = getYear + "/" + getDataCountDown;
      $(this).data("countdown", newData); 
    });
    

    UPDATE

    As Jaromanda X said it won't change DOM, if we need to change DOM also means we can go for

    $(this).attr("data-countdown", newData);
    

    instead of

    $(this).data("countdown", newData);