Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js text formatting and classes

First time posting. So I have to format some text in a element that looks like this

<div class="entry-time">
  2012-05-30T20:11:06+00:00 
</div>

I'm trying to format this out to something more readable with moment.js. I can only do this from the front end with javascript. I wrote a function that looks like this.

$(document).ready(function() {
    function formatDate(date) {
        formattedDate = date.text();
        var d = moment(formattedDate, "YYYY-MM-DDTHH:mm:ss");
        $(date).html( d.format("dddd, MMMM Do YYYY, h:mm:ss a"));
    };

    formatDate($('.entry-date'));
});

This works if there is one element but when there are multiple elements it will format everything into one date. I know this has something to do with jQuery pulling in an array of elements but I have no idea how to do what I did to each element with the class of entry-date.

Can anyone help? Thank you in advance.

like image 333
tastytoast Avatar asked Jan 17 '23 12:01

tastytoast


1 Answers

At the heart of what's wrong is that the jQuery .text() method gets "the combined text contents of each element in the set of matched elements, including their descendants" (api.jquery.com/text) rather than iterating over the set of elements as you intend.

Something like this should work, passing a function into the jQuery .html() setter method:

$(".entry-date").html(function(index, value) {
    return moment(value, "YYYY-MM-DDTHH:mm:ss").format("dddd, MMMM Do YYYY, h:mm:ss a");
});
like image 144
John Madhavan-Reese Avatar answered Jan 27 '23 04:01

John Madhavan-Reese