0

I'm attempting to grab the value of a data attribute:

<div class="relative-time" data-seconds="1449907467">12 December 2015</div>

As you see, the value is a Unix epoch time, so the value varies.

So far I've tried...

$(".relative-time[data-seconds='/[^0-9]+/']");
$( "body" ).data( "data-seconds", /[^0-9]+/ );
$('div[data-seconds="/[^0-9]+/"]');
$("body").attr("data-seconds");
$('*[data-seconds="/[^0-9]+/"]');

... But none of these return anything.

Assuming the regular expression was not correct, I swapped it out for the actual value, but there was no change.

Any ideas would be welcome.

1
  • 2
    You want $('.relative-time').data('seconds') - you omit the data- prefix when using the .data() method. Note that jQuery attribute-equals selectors do not support testing against regexes. Note also that $('body').data('seconds') is not going to work, since the <body> element is not the one with the data-seconds attribute. Note further that you seem to be very confused about what the two-argument form of .data() does. I recommend reading the jQuery documentation rather than blindly guessing. Commented Dec 13, 2015 at 20:19

1 Answer 1

1

Get the value

$('.relative-time').data('seconds');

Change to Date

new Date($('.relative-time').data('seconds') * 1000));

Print to console

console.log(new Date($('.relative-time').data('seconds') * 1000));

on jsfiddle

UPDATE

Or with a jQuery prototype function:

(function($) {
   $.fn.setDate = function() {
     this.text(new Date(this.data('seconds') * 1000));
     // or return value
     // return new Date(this.data('seconds') * 1000);
   }
})(jQuery);

To read and set Value:

$(".relative-time").setDate();

on jsfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Hi MoonYard, and thank you! Part of the problem is because I'm attempting to do this within a function. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.