jQuery: formatting letters

In this post I'm going to show you how to format letters with jQuery. To accomplish this task, I'm going to create a very simple plugin that will separate the letters of a word and wrap them with an HTML element that, in turn, will have a progressive CSS class attached to it (such as class1, class2 and so on). Let's start with the plugin, called letters():

(function($) {
    $.fn.letters = function(cssClass) {
          cssClass = cssClass || 'letter';
          var text = this.text();
          if(!/^[a-z]+$/i.test(text)) {
                throw new Error('This plugin requires a string of text to work.');
          var counter = 0, html = '', i;
          for(i = 0; len = text.length, i < len; i += 1) {
              counter += 1;
              html += '<span class="' + cssClass + counter + '">' + text[i] + '</span>';
          return this;

This plugin uses the nodeValue property returned by the text() method. As you can see, the plugin needs to work only with a single word, without spaces. To make sure that its value is in the correct format, a basic test with regular expressions will check if everything is correct. If not, a JavaScript error will be returned. Then this plugin iterates over the string that makes up the text node of the element, separating all the letters contained within and wrapping them with a span element that has a progressive CSS class as its sole attribute. Finally, the textual content of the element is replaced with the newly created content. Note how this plugin accepts only one option, namely the CSS class used with all the letters.

A simple test:

$(document).ready(function() {



You can see the results here. The jQuery plugin is available at this address.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

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