Friday, August 31, 2012

jQuery has ruined my Javascript - here are some fallbacks

It's true. Using jQuery is likely to make you forget how to do fundamental things in javascript. Some people get all riled up about this because jQuery is just a library, meaning its only javascript anyway.  The way jQuery allows selectors to be written is reason enough to utilize it. Compare these examples:

A) $("#first_paragraph").text("Booya");
B) document.getElementbyId("first_paragraph").innerHTML = "Booya";

jQuery accomplishes the same thing in half as many characters.

There are times when a customer wants something written in pure javascript. I suppose they're trying to avoid licensing and compatibility issues that might come with using libraries.

Anyway, long story short, here are the javascript equivalents of some of my favorite jQuery functions:

// works like the $(".classname") selector
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

// same as $.inArray()
function contains (needle,haystack) {
   for (var i=0; i < haystack.length; i++) {
      if (needle == haystack[i]) {
         return true;
      }
   }
   return false;
}

// counts the frequency of identical indices in an array
// I'm not sure if there is a jQuery equivalent of this but I love the function in PHP!
function arrayFreq(myArray) {
   var myBlocks = new Object ;

   for (var i=0; i<myArray.length; i++) {
      var aBlock = myArray[i] ;
      if (myBlocks.hasOwnProperty(aBlock)) {
         myBlocks[aBlock]++ ;
      } else {
         myBlocks[aBlock] = 1 ;
      }
   }
   return(myBlocks);
}

No comments:

Post a Comment