Skip to content
This repository

"cupQ" (aka "cupQuery")is an easy-to-use cross-browser open source JavaScript framework that allows querying and manipulation of HTML DOM document using standard selectors to get output as an array of result values. With cupQ, controlling HTML DOM is now everybody's cup of tea!

Author: Samir Dash, mobilewish@gmail.com :: http://samirshomepage.wordpress.com ** **Download: https://github.com/mobilewish/cupQ License: MIT License. Version: 0.2 Published: June 2012


What's new in this version?

  1. Added support for plugin architecture. Now extending cupQ is also everybody's cup of tea!Anyone can now create plugins for cupQ to add powerful features.
  2. Disabled auto initialisation of browser detection, which was there in v 0.1. Now the developer has to initialise it manually if required.
  3. Now each cupQ object instance is created, it will have an unique ID, which will appear in trace(), that will allow developers to easily track the target instance from debug information from the console .
  4. cupQ initiation method now by default does not return the result array of nodes list . The init() method now returns the cupQ object. This is a major change.
  5. For nodes List we can now use cupQ property "nodesArray" (e.g. _().init().nodesArray )or a new method called "getNodesArray()" (e.g. _().init().getNodesArray() or _().getNodesArray() ) ***

USAGE - OVERVIEW:

Any cupQ method always returns results in a form of an array. So to track any individual values of the result you can always use index to specify the resulting item in the result array.

The cupQ object can be initiated using the "_()".

Sample usage can be : _().setDebug(true);

Instead of directly using "_()", you can assign a variable to it so that you can refer to the same cupQ object multiple times -- this helps in avoiding multiple instance of the cupQ object. So the previous example can be written as

var myCupQ = _();
myCupQ.setDebug(true);

Querying HTML DOM can only be done after the document is ready. So after basic setup like allowing debug mode or the similar, the on document ready event can be setup as follows:

var myCupQ = _();
myCupQ.onDocumentReady= function (){

    //add your code here that you want to load after dom is loaded or the document is ready...for example the following line is called after the document is ready 
    myCupQ.importFiles(["js/importscripts.js"]);

    //here you can use multiple cupQ objects ..like the one in the following is a different one that the previous line
    _().importFiles(["js/importMyNewScripts.js"]);



}

USAGE - QUERYING DOM USING SELECTORS:

For querying dom the expression involves 3 parameters .

    _(selector, targetNode, indexQueryResultingArray).init().getNodesArray();

"selector" is a string which can be a class name, an element id or simply a tag name. 
For class name the "selector" must be prefixed with a dot "." and for an id there must be a prefix of a hash "#"  

"targetNode" can be document or any DOM node or an array with nodes. This is optional (but in case the third parameter is "indexQueryResultingArray" is specified , you need to specify this one). If no value is supplied, the querying starts with the document object element of the DOM. 

"indexQueryResultingArray" is either a zero (0) based index number, or an array of numbers or a string with expression or a function that can be passed  that can target which node or nodes to pick if the query results in a list of nodes or a collection of DOM elements.
Using 0 is the first item in the resulting nodes list, and using -1 will refer to the last item in the resulting array if applicable. This parameter is optional. 

To get query output as an array of resulting nodes, the "getNodesArray()" is called for the target cupQ object. 

examples :

option: 1   (as a method call)

                var myCupQ = _("p").init();                 
                myCupQ.getNodesArray(); //returns array of resulting nodes 


                or simply use

                _("p").init().getNodesArray(); //returns array of resulting nodes 



option 2    (as a property)     


                var myCupQ = _("p").init();                 
                myCupQ.nodesArray; //returns array of resulting nodes 


                or simply use

                _("p").init().nodesArray; //returns array of resulting nodes 

In the following are different types of usage of selectors to get the array of resulting nodes from the DOM:

Get array of nodes having the class name. For example for a class name "className" the expression will be as follows:
    _(".className").init().getNodesArray();

Get current node  as an element of an array with the id name. For example for a id name "idName" the expression will be as follows:
    _(".idName").init().getNodesArray();

Get the first node as an element of an array with the specified class name. 
    _(".className", document, 0).init().getNodesArray();

Get the last node  as an element of an array with the specified class name  
    _(".className", document, -1).init().getNodesArray();

Get array of nodes with the class names appearing with odd positions -- here the expression "odd" is used as 3rd parameter. 
_(".className", document, "odd").init().getNodesArray();

Get array of nodes with the specified class names appearing with even positions -- here the expression "even" is used as 3rd parameter.
_(".className", document, "even").init().getNodesArray();

Get array of nodes with the specified class names appearing with positions mentioned in the array-- here the array of index numbers is used as 3rd parameter.. Note the array contains indexes that are 0 based. 
_(".className", document, [1, 2, 4, 5]).init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the expression i.e. position numbers > 4 in this example. Note the expression contains index that is 0 based.
_(".className", document, ">4").init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the expression i.e. position numbers == 4 in this example. Note the expression contains index that is 0 based.
_(".className", document, "==4").init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the expression i.e. position numbers < 4 in this example. Note the expression contains index that is 0 based.
_(".className", document, "<4").init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the expression i.e. position numbers >= 4 in this example. Note the expression contains index that is 0 based.
_(".className", document, ">=4").init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the expression i.e. position numbers <= 4 in this example. Note the expression contains index that is 0 based.
_(".className", document, "<=4").init().getNodesArray();

Get array of nodes with the class names appearing with positions as per the out put based on the function "myFunction" ...like you can use a function that compares certain things to decide which nodes to choose.
_(".className", document, myFunction).init().getNodesArray();

    where 

    myFunction = function (){   return [3, 5, 9];   }

USAGE - GETTING THE PARENT NODE OR CHILD NODES OF THE PROVIDED SELECTORS:

Getting array of parent and child nodes from document after querying using the specified selector. This includes [objectText] if there is no nodes present but some text present. For example in side paragraph only text is there.

Get the array containing unique parent node of resulting nodes after querying using the specified selector (for example here the class name is used )
_("-.className", document, -1);

Get the array of child nodes of resulting nodes after querying using the specified selector (for example here the class name is used )
_("+.className", document, -1);

USAGE - QUERYING DOM USING SEQUENCE/TREE OF SELECTORS:

There is a nice feature of cupQ that allows you to provide a string of sequence/tree of selectors (excluding the document object element) to get the resulting node. Each selector has to be separated by a single blank space .

Parent and child nodes expressions can also be used :

Example: 

(_("p[1] span[0]").init().getNodesArray());//sequence of selectors 

(_("-p[1] span[0]").init().getNodesArray());//parent of sequence of selectors 

(_("+p[1]").init().getNodesArray());//array of children  of sequence of selectors 

USAGE - QUERYING DOM FROM CUSTOM NODE ON WARDS:

By default, the cupQ starts Querying the HTML DOM from the root or the 'document' object element. But this can be customised to start querying from any specific node of the DOM by supplying "targetNode" which can be document or any DOM node or an array with nodes.

Example of getting nodes from custom node

var targetNode = document.getElementById("myId");
Note: instead of using DOM methods above, you can even use cupQ to get the targetNode e.g. _("#myId").init(); 

_(".idName", targetNode);//get current node with the id name from the target Node onwards 
_(".className", targetNode);//get array of nodes from the target Node onwards with the class name
_(".className", targetNode, 0);//get first node from the target Node onwards with the class name
_(".className", targetNode, -1);//get last node from the target Node onwards with the class name

Example of getting nodes (arrays) from an array containing custom nodes

var targetNode = [document.getElementById("myId"),document.getElementById("myId2") ];
Note: instead of using DOM methods above, you can even use cupQ to get the targetNode e.g. [_("#myId").init(), _("#myId2").init()]; 

_(".idName", targetNodesList);//get current nodes (array) with the id name from the target NodesLists onwards 
_(".className", targetNodesList);//get array of nodes from the target NodesLists onwards with the class name
_(".className", targetNodesList, 0);//get first node from the target NodesLists onwards  with the class name
_(".className", targetNodesList, -1);//get last node from the target NodesLists onwards  with the class name

USAGE - QUERYING AND MANIPULATING HTML DOM:

Using cupQ, You can do lot more than just querying HTML DOM to get array of nodes or HTML elements. You can use getter / setters to target and manipulate different nodes and their attributes, styles, html and text contents.

.html(val, index)
------------------
This is a both getter and setter to grab and manipulate the innerHTML of the target node(s). If no parameter is supplied, the method acts as a getter and returns the innerHTML of the target node(s) as an array. 
If parameter "val" is supplied then the value is set to the innerHTML of the target node(s). If index is supplied, then only the target node with thye specified index in the array of the reulting nodes is modified or the value is granbbed from. 

e.g:
_("#idName").html();//get inner html
_("#idName").html("<b>hello</b>");//update inner html
_("p").html("hello", 0);//update inner html for the 0 indexed paragraph among the resulting array of paragraphs obtained after the query is executed.


.htmlAppend(val, index)
-------------------------
This is a setter method (which also returns the final updated inner html )that appends  (adds content at the end of existing one) the provided content (via the "val" parameter) and also can work on specific indexed item in the resulting nodes.

e.g:
_("-p").htmlAppend("<b>hello</b>", 1);//appends to inner html



.htmlPrepend(val, index)
-------------------------
This is a setter method (which also returns the final updated inner html )that pre-pends (adds content at the begining of existing one) the provided content (via the "val" parameter) and also can work on specific indexed item in the resulting nodes.

e.g:
_("-p").htmlPrepend("<b>hello</b>", 1);//prepends to inner html



.text(val, index)
------------------
This is a both getter and setter to grab and manipulate the inner text (innerText) of the target node(s). If no parameter is supplied, the method acts as a getter and returns the inner text of the target node(s) as an array. 
If parameter "val" is supplied then the value is set to the inner text of the target node(s). If index is supplied, then only the target node with thye specified index in the array of the reulting nodes is modified or the value is granbbed from. 

e.g:
_("#idName").text();//get inner text
_("#idName").text("hello");//update inner text
_("p").text("hello", 0);//update inner text for the 0 indexed paragraph among the resulting array of paragraphs obtained after the query is executed.


.textAppend(val, index)
-------------------------
This is a setter method (which also returns the final updated inner text )that appends  (adds content at the end of existing one) the provided content (via the "val" parameter) and also can work on specific indexed item in the resulting nodes.

e.g:
_("-p").textAppend("<b>hello</b>", 1);//appends to inner text



.textPrepend(val, index)
-------------------------
This is a setter method (which also returns the final updated inner text )that pre-pends (adds content at the begining of existing one) the provided content (via the "val" parameter) and also can work on specific indexed item in the resulting nodes.

e.g:
_("-p").textPrepend("hello", 1);//prepends to inner text



.remove(index)
-------------------------
This is a setter method that removes the resulting nodes and returns blank array if no index is spplied. If index is supplied, it removes the target node selecting it from the resulting array of nodes and returns the updated array of resulting nodes. 

e.g:
_("p").remove();//removes all the nodes
_("p").remove(1);//removes node of the mentioned index



.style()
-------------------------
This returns the array of style objects for the target nodes selected after querying using the selctors. Each individual style object can be then accessed using native DOM methods to manipulate for both getter and setter related activities. 

e.g:
_("p").style();//get array of style objects for the resulting nodes
_("p").style()[2];//get the target style object for corresponding index from the array of style objects obtained from the resulting nodes
((_("p").style())[0]).width='2440px';//setting the individual style "width" for any target style object
(_("p").style(0)[0].backgroundColor);//getting individual style for any target style object




.attribute(attributeName, indexQueryResultingArray, attributeValue)
----------------------------------------------------------------------------
This can be both getter and setter to manipulate attributes of the target nodes. 

attributeName - this is the name of the attribute you want to grab or set the value for.
indexQueryResultingArray - this is optional. supply an index number to target the node in the resulting array of nodes. If 3rd parameter is used and you do not want to supply index use "" which will set it to default. 
attributeValue - this is optional. If supplied, this value will be set to the target attribute. 

e.g:
(_("p").attribute("name"));//getter - here the target attribute is "name"
(_("p").attribute("style", "", "background:yellow"));//setter - without using any index (so that it affects all the nodes in the array )using setter for a attribute called "style" - alternative way to manipulate style of a node
(_("p").attribute("style", 1, "background:yellow"));//setter - using index (so that it affects only target indexed node )using setter for a attribute called "style" - alternative way to manipulate style of a node



.childIndexInParent(indexQueryResultingArray)
----------------------------------------------------------------------------
This is a getter that returns an array of index numbers for each ttarget nodes in their parent nodeList. If indexQueryResultingArray is supplied it returns only the index of the target node in it's parent nodeList. 

e.g:
(_("p").childIndexInParent());//get index numbers of the nodes selected under their parent node;
(_("p").childIndexInParent(2))//for specific selected node ..the child index number of it in it's parent node 

USAGE - PROPERTIES

.version - returns version number of cupQ library used.
.currentObjectId - returns the unique instance object Id of the cupQ object. 
.Q  - returns the query.
.isClassName- returns true if the query provided is a class name.
.isIdName- returns true if the query provided is for an element id in HTML DOM.
.isTagName- returns true if the query provided is for a HTML tag name.
.isGetParent- returns true if the query provided is for selecting the parent nodes (unique) for the target nodes based on current query.
.isGetChildren- returns true if the query provided is for selecting the child nodes for target nodes based on current query.
.isGetCurrent - returns true if the query provided is for selecting the target nodes based on current query.
.nodesArray - returns the array of the resulting target nodes for the provided queries.
.childIndexInParentArray - returns the array of parentNodes of the resulting target nodes for the provided queries.
.attributeArray - returns the array of attribute values (of provided attribute name) content of the resulting target nodes for the provided queries.
.styleArray - returns the array of style attribute values of the resulting target nodes for the provided queries.
.innerTextArray - returns the array of text content of the resulting target nodes for the provided queries.
.innerHTMLArray - returns the array of HTML content of the resulting target nodes for the provided queries.
.targetArray - returns the array of target nodes which are used as the root nodes for multiple queries.
.bodyFilesArray  - returns the array of JavaScript / CSS file paths to be added in the body of the HTML DOM .
.headFilesArray   - returns the array of JavaScript / CSS file paths to be added at the header of the HTML DOM .
.pluginsArray   - returns the array of plugins resgitered with cupQ. 

USAGE - BROWSER SNIFFING:

The cupQ sniffs for the browser and opertaing system when an instance of cupQ runs. The sniffing details can be found from properties of ".hostObject" .

Before getting browser, navigator and OS details, the initialisation has top be done through calling init();

    e.g:

    var myCupQ = _();

    //now initialising the hostObject. 
    myCupQ.hostObject.init();

    //now get the details 
    myCupQ.hostObject.browser;
    myCupQ.hostObject.version;
    myCupQ.hostObject.OS;
    myCupQ.hostObject.navigator;
    myCupQ.hostObject.navigatorVendor;
    myCupQ.hostObject.userAgent;

USAGE - UTILITIES:

There are a few utilities methods available.

.getUniqueArray(myArray)
--------------------------
This returns an array with unique items from the supplied array of items. 

USAGE - SETTINGS AND DEVELOPER UTILITIES:

_().setDebug(val);
-----------------
This is a global flag that either turns on the debug mode (to allow "trace" messages in the browser console.) -- if you set this in any instance it will affect all the instances of cupQ running in that document.
The parameter can be true or false boolean value. 
The default is false. 

e.g:
_().setDebug(true);//true sets global debug mode on.


The debug value can be read through the property "debug"  

_().debug; // returns the value true or  false



_().trace(val);
-----------------
This iallows you to log your message to console window of the browser. This only writes to console only if the debug value is set to true. 
This is an easy to maintain feature that you can use to log your JavaScript messages to console, as you can turn on or off it using the debug mode. 

 Now each cupQ object instance is created, it will have an unique ID, which will appear in trace(), that will allow developers to easily track the target instance from debug information from the console . 
For example an out put will be like the following : "[CUPQID1340363887134000] cupQ: onDocumentReady() called."

Using trace is straightforward: 
e.g:
_().trace(message);//passing value of message to console
_().trace("some message");// only if the debug mode is on it logs the message to console;

USAGE - EXTENDING CUPQ OBJECT WITH PLUGINS - WRITING SAMPLE PLUGIN:

From v0.2 onwards the support for plugin has been added. Now extending cupQ is also everybody's cup of tea!Anyone can now create plugins for cupQ to add powerful features.

To add a plugin, the plugin object is passed to cupQ instance via "register" method of the "pluginManager" object of cupQ.

Any plugin resgitered with any instance of cupQ object is available only for that instance.

Typical syntax to register is as follows:

_().pluginManager.register("pluginShortname", pluginObject  );

Note: The register plugin can be called even before calling init() method.

A plugin object san be a simple Java Script Object having the methods and properties.

An example of a simple plugin is shown below that return current time (Date object) on initiation. Notice it has an object called "getInfo" which returns the information about the plugin. It is required to include this "getInfo" object while developing plugins.

        var myCupQ = _();
        myCupQ.pluginManager.register("someplugin", 
            {
                init:function(){
                                var sampleValue = new Date();
                                return(sampleValue);
                            },


                getInfo : {

                            longName : 'sample plugin  name',
                            author : 'Some Author Name',
                            authorURL : 'http://theurloftheauthorswebsite.com',
                            infoURL : 'http://theurlofthepligininfowebsite.com/plauginname',
                            version : "1.0"

                        }           

            }

        );

The "getInfo" must have the following properties defined -- "name", "longName", "author", "authorURL", "infoURL" and "version".

Within plugin the parent object (i.e. the instance of cupQ) can be accessed using ".parent". For example in the following the plugin returns the version of the parent cupQ object.

        var myCupQ = _();
        myCupQ.pluginManager.register("someplugin", myPlugin); 


        var myPlugin = {
                init:function(){

                                return(this.parent.version);
                            },


                getInfo : {


                                        longName : 'sample plugin  name',
                                        author : 'Some Author Name',
                                        authorURL : 'http://theurloftheauthorswebsite.com',
                                        infoURL : 'http://theurlofthepligininfowebsite.com/plauginname',
                                        version : "1.0"

                        }           

            }

if the plugin is registered after the init() method of thye cupQ object is called, it can also get the resulting query result through calling to parent methods. The following example makes use of the "nodesArray" property of its parent cupQ object.

            var myCupQ = _();
            myCupQ.onDocumentReady=function(){
        myCupQ.pluginManager.init().register("someplugin", myPlugin); 


        var myPlugin = {
                init:function(){

                                return(this.parent.nodesArray);
                            },


                getInfo : {


                                        longName : 'sample plugin  name',
                                        author : 'Some Author Name',
                                        authorURL : 'http://theurloftheauthorswebsite.com',
                                        infoURL : 'http://theurlofthepligininfowebsite.com/plauginname',
                                        version : "1.0"

                        }           

            }
            }

Example of plugin info being tracked -

    myCupQ.someplugin.getInfo;//returns the getInfo Object of the plugin 
    myCupQ.someplugin.getInfo.longName;//returns the long name of the plugin 
    myCupQ.someplugin.getInfo.author;//returns the author name of the plugin 
    myCupQ.someplugin.getInfo.authorURL;//returns the author URL of the plugin 
    myCupQ.someplugin.getInfo.infoURL;//returns the info URL of the plugin 
    myCupQ.someplugin.getInfo.version;; //returns the version of the plugin     

USAGE - WRITING CUPQ EXTENSIONS (i.e. PRE-REGISTERED STANDALONE PLUGINS) :

Using the method described in the previous section, any cupQ instance object can be extended. But in such method the plugin has to be registered to any cupQ object in the runtime. In case you want to distribute pre-registered plugin i.e. your plugin enabled extended cupQ object, you can create a cupQ object instance and regsiter your plugin with it. Next wrap it with a method with an extension name. Now you place all these code into a separate javaScript file for distribution.

Following is an example of a preregistered plugin (the following code has to be placed in a separate JavaScript file):

            var myCupQExtension = function(selector, targetNode, indexQueryResultingArray){

            var myCupQ = _(selector, targetNode, indexQueryResultingArray);
            myCupQ.onDocumentReady=function(){


            var myPlugin = {
                init:function(){

                                return(this.parent.nodesArray);
                            },


                getInfo : {


                                        longName : 'sample plugin  name',
                                        author : 'Some Author Name',
                                        authorURL : 'http://theurloftheauthorswebsite.com',
                                        infoURL : 'http://theurlofthepligininfowebsite.com/plauginname',
                                        version : "1.0"

                        }           

                }

                myCupQ.pluginManager.init().register("someplugin", myPlugin); 


                }

            }();        




The above extension can be used just like any native cupQ object with the plugin objects enabled. 

        myCupQExtension("p").html();
        myCupQExtension(".className").someplugin.init();            



        Check "extension" folder in the cupQ github repository for more samples. 
Something went wrong with that request. Please try again.