Wayne Smallman
Wayne Smallman

Reputation: 1720

jQuery: Find data attribute with regex

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.

Upvotes: 0

Views: 892

Answers (1)

user2741005
user2741005

Reputation:

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

Upvotes: 1

Related Questions