af83

$(Nicer) - a nicer dollar javascript function, prototype style

You must know the $ Function in prototype (also in jQuery and mootools) that helps you target elements in Javascript. Well, here's my take on it.

Here's the code :

function $( magic , node ){
      //model : [@][id][:][tag]

      var keys = /^([\@]*)([\w+]*)([\:]*)([\w+]*)$/(magic);
      var isArray = keys[1];
      var id = keys[2];
      var tag = keys[4];

      if( tag == "" ){tag = "*"}
      if( node == undefined ){ node = document }

      var nodes = node.getElementsByTagName(tag);
      var ret = new Array;
      for( var i=0; i < nodes.length; i++ ){
            if( id != "" && nodes[i].id != id ){continue}
            ret.push( nodes[i] );
      }

      if( isArray == "@" ){
            return ret;
      }else{
            return ret[0];
      }

}

How to use it :

$("mainHeader")

: returns the first node in document having "mainHeader" for id and anything for tag name.

$("clickMe:a")

: returns the first node in document having "clickMe" for id and "a" for tag name.

$("@clickMe:a")

: returns all nodes ( as an array ) in document having "clickMe" for id and "a" for tag name.

$("@:div")

: returns all divs in document.

$(":img")

: returns first img in document

$("@clear:div" , subNode )

: returns all nodes in DOM node "subNode" having "clear" for id and "div" for tag name.

$("@")

: returns all DOM nodes in document.

And so on …

blog comments powered by Disqus