Question

Question: How do I convert each title individually into ISO8601

I am trying to utilize the timeago JQuery library. I populate the title with UTC string, so I have to convert the UTC attr title to ISO8601 before running the Timeago library, otherwise Safari/FF/IE show nothing.

JQuery

var dateString = $('.timeago').attr('title');
var dateConvert = new Date(dateString);
 $('.timeago').attr('title', dateConvert.toISOString());

HTML

<abbr class="timeago" title="Sun, 30 Jul 2014 15:06:00 -0500"></abbr>
<abbr class="timeago" title="Sun, 30 Jul 2014 14:45:00 -0500"></abbr>

Results

<abbr class="timeago" title="2014-07-30T20:06:00.000Z">3 minutes ago</abbr>
<abbr class="timeago" title="2014-07-30T20:06:00.000Z">3 minutes ago</abbr>

Expected Results

<abbr class="timeago" title="2014-07-30T20:06:00.000Z">3 minutes ago</abbr>
<abbr class="timeago" title="2014-07-30T19:45:00.000Z">24 minutes ago</abbr>
Was it helpful?

Solution

Your code only is grabbing the title attribute of the first .timeago element.

[jQuery's attr()][1] method "[gets] the value of an attribute for the first element in the set of matched elements or [sets] one or more attributes for every matched element" (docs).

Use jQuery's .each method if you want to perform an action on each selected element in a set:

$(".timeago").each(function() {
    var dateString = $(this).attr('title');
    var dateConvert = new Date(dateString);
    $(this).attr('title', dateConvert.toISOString());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top