I am pulling an RSS feed
onto my site which contains a date in the format dd/mm/yyyy (UK date format)
. The dates are wrapped in h3 tags
, I would like to replace the original date with 2 divs containing only the date and the month respectively. I've managed to achieve this but the date outputted is the same for every instance.
How can I replace the date in each respective div? I've tried all sorts but I can't quite figure it out. No doubt there is a far simpler way to do it! Any help is greatly appreciated.
The HTML is:
<div class='news'>
<h2>Title</h2>
<h3>11/06/2013</h3>
<p>Content</p>
</div>
<div class='news'>
<h2>Title</h2>
<h3>07/06/2013</h3>
<p>Content</p>
</div>
And the javascript is:
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]; // Define month names array
$(".news h3").each(function () {
// Gets date and puts it in variable 'postDate'
var postDate = $(this).html();
// Reformats date into UK format after Javascript date object is created
var d = new Date(postDate.split('/')[2], postDate.split('/')[1] - 1, postDate.split('/')[0]);
$('.news h3').replaceWith('<div class="blogDate">' + d.getDate() +
'</div><div class="blogMonth">' + monthNames[d.getMonth()] +
'</div>'); //Replaces original date with newly created divs
});
I've created a JSFiddle so you can see the output . The bottom date should read 7 Jun
.
You need to replace the content of the current h3
instead of replacing all
$(this).replaceWith('<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>');
Demo: Fiddle
More correct fix
$(".news h3").replaceWith(function(){
var postDate = $(this).html();
var parts = postDate.split('/');
var d = new Date(parts[2], parts[1] - 1, parts[0]);
return '<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>';
})
Demo: Fiddle
If you can include a date-time library momentjs then
$(".news h3").replaceWith(function(){
var text = moment($.trim($(this).text()), "DD/MM/yyyy").format('D MMM');
return '<div>' + text + '</div>';
})
Demo: Fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.