Archive for February, 2007

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 :

JavaScript:
  1. function $( magic , node ){
  2.       //model : [@][id][:][tag]
  3.  
  4.       var keys = /^([\@]*)([\w+]*)([\:]*)([\w+]*)$/(magic);
  5.       var isArray = keys[1];
  6.       var id = keys[2];
  7.       var tag = keys[4];
  8.      
  9.       if( tag == "" ){tag = "*"}
  10.       if( node == undefined ){ node = document }
  11.      
  12.       var nodes = node.getElementsByTagName(tag);
  13.       var ret = new Array;
  14.       for( var i=0; i <nodes.length; i++ ){
  15.             if( id != "" && nodes[i].id != id ){continue}
  16.             ret.push( nodes[i] );
  17.       }
  18.      
  19.       if( isArray == "@" ){
  20.             return ret;
  21.       }else{
  22.             return ret[0];
  23.       }
  24.  
  25. }

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 ...

Click to continue reading

Creative Commons License
This work is licensed under a Creative Commons Attribution 2.0 License.