Automatic Fancy Ampersands with jQuery

Average reading time is

Back in 2008, Dan Cederholm posted a great design tip on CSS-based fancy ampersands. The basics of this technique is that you surround every & in your headers with a <span class="ampersand"> tag. Then, in CSS, you define .ampersand as something like the following:

span.ampersand {
  font-family: Baskerville, Palatino, "Book Antiqua", serif;
  font-style: italic;
  font-weight: normal;
}

…or, in Sass:

.ampersand
  :font-family Baskerville, Palatino, "Book Antiqua", serif
  :font-style italic
  :font-weight normal

Fancy ampersands are one of those little details that adds a subtle aesthetic touch, and gives the page an extra notch of professionalism. Unfortunately, adding those spans by hand is both bothersome, and error-prone. It also becomes difficult to make use of this technique for existing or automatically generated content.

Luckily, that's why god created jQuery!

With a little addition to our application.js, we can have fancy ampersands inside all of our header tags (h1, h2, etc.):

$(document).ready(function(){
  $(":header:contains('&')").each(function(){
    $(this).html($(this).html().replace(/&amp;/, "<span class='ampersand'>&amp;</span>"))
  });
});
Feel free to submit corrections via github