JavaScript: formatting Blogger dates

Today I wanted to format all my post dates using a custom background image that I've found in one of these useful web graphics packs on a web site. For this blog, I've chosen the format Day, Month DayNumber, Year, that is, Thursday, April 14, 2011. The problem is that the markup used by my template uses a single h2 element with the CSS class date-header associated to it. That is:

<h2 class="date-header">Thursday, April 14, 2011</h2>

Instead, my image is divided into two main color areas, as you can see below:

So here I had to turn the current format into April 14, 2011 and the corresponding markup into the following one:

<h2 class="date-header">
  <span class="month">April 14</span>
  <span class="year">2011</span>

I didn't want to play with my date settings, so I've used the following JavaScript code:

var h2 = document.getElementsByTagName('h2');
for(k = 0; k <h2.length; k +=1) {

  var elem = h2[k];
  if(elem.className == 'date-header') {
    var text = elem.firstChild.nodeValue;
    var parts = text.split(',');
    var month = '<span class="month">' + parts[1] + '</span>';
    var year = '<span class="year">' + parts[2] + '</span>';

    elem.innerHTML = month + year;



I've basically split the text node of the heading using the comma as a separator and then I've assembled the resulting string to be used with the innerHTML property. I think it's working, but honestly this is the kind of thing that would require a specific widget, IMHO. wink

Leave a Reply

Note: Only a member of this blog may post a comment.