toofishes.net

Why JS libraries are timesavers

If you have ever home-rolled JavaScript to do DOM traversal and manipulation, you know it is a painful experience. It is especially apparent when working on a legacy project where you end up adding to the mess, but I offer this advice- move to a JS library as quickly as possible.

I wrote up the following code the other day before I realized I should just grab a library. The idea is to apply a CSS class on the fly to <code/> elements in my blog. This allows the prettify code to come though and highlight it, as it works by finding all elements with a given class.

function makePretty() {
  var possibleCode = document.getElementsByTagName('code');
  for (var i = 0; i < possibleCode.length; ++i) {
    // Apply the pretty-printing to all parents if they are a 'pre'
    p = possibleCode[i].parentNode;
    if (p.tagName.toLowerCase() === 'pre') {
      p.className = 'prettyprint';
    }
  }
  prettyPrint();
}

jQuery comes to the rescue and makes this a breeze to code, and in one line at that.

function makePretty() {
  // Apply pretty-printing to code elements inside a pre tag
  $('pre > code').addClass('prettyprint');
  prettyPrint();
}

Yes, I know the two code snippets do something slightly different (which element ends up getting the ‘prettyprint’ class applied), but the end result was the same, and it was accomplished with a lot less effort on my part.

Between jobs and personal projects, I’ve used YUI, prototype, and jQuery. I don’t want to advocate any of these over others as I think they all have their roles, but I would recommend sticking with only one in a given project if at all possible.

Tags

See Also