How to use data attribute value inside Javascript code?

I want to use the data attribute value inside Javascript code. I have a simple code for countdown timer from W3 Schools. Where I need to write Countdown Last Date, or completing Date. But I want something like that, data-attribute value will be place inside the Last date position. Look at this code;

<p id="demo"></p>

<script>
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);


document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

I want something like that;

<p id="demo" data-attribute="Jan 5, 2024 15:37:25"></p>

This data attribute value or time will be place inside var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();

So that it can change from HTML Part. don’t need to go Javascript code. If there’s any way using jquery, I will do. how can I do it ?

Show or use data-attribute value inside Javascript Code.

>Solution :

To access the value of a data-* attribute in JavaScript, you can use the getAttribute() method and pass in the attribute name.

For example, if you have an element with a data-time attribute like this:

<p id="demo" data-time="Jan 5, 2024 15:37:25"></p>

You can access the value of the data-time attribute like this:

var time = document.getElementById('demo').getAttribute('data-time');

Then you can use the time variable in your JavaScript code, such as when creating a new Date object like this:

var countDownDate = new Date(time).getTime();

You can also use jQuery to access the data-time attribute like this:

var time = $('#demo').attr('data-time');

Then you can use the time variable in your JavaScript code in the same way as shown above.

Leave a Reply