Jumping in and out of jQuery land

Recently I started using jQuery in some projects. In past projects I have mainly been using Prototype and the fact that jQuery also has a $() function made me feel at home right away. That same fact put me a bit off-guard as both functions are in fact quite different:

  • Prototype extends the selected HTML node with added functionality and returns it. Argument should be a HTML node or element id.
  • jQuery selects the HTML node (or nodes) and stores the selection in a jQuery object, which then is returned. Argument should be a css-like selector.

So, as opposed to Prototype, jQuery’s $() method can select a single element as well as a collection of elements. The existence of Prototype’s $$() function also kind of suggests that Prototype’s $() doesn’t do that. And… when passing just an id to jQuery’s $() (e.g. $(‘myDiv’)) it is discovered soon enough that nothing is selected but air.

By using jQuery’s $() functionwe’re leaving the DOM-zone and enter jQuery land. Although jQuery can do a lot, situations might occur where one needs to get the ‘real’ DOM elements. For instance, to pass them as argument to components that don’t talk jQuery. Luckily it’s just as easy to go back, by using the get() accessor.

Some simplified HTML code example boxes:

<div class="codeBox">
  <a href="#">copy to clipboard</a>
      <code>Some code</code>
  
</div>


<div class="codeBox">
  <a href="#">copy to clipboard</a>
      <code>More code</code>
  
</div>

Accompanied by the following javascript:

$(document).ready(function(){
    initCodeBox();
});

function initCodeBox()
{
    $('.codeBox a').bind('click',function() {
        var htmlNode = $(this).siblings('code').get(0);
        if (htmlNode) copyContentsToClipboard(htmlNode);
        return false;
    });
}

function copyContentsToClipboard(htmlNode)
{
        // js selecting the text contents of a DOM node, simplified to: 
    alert(htmlNode.innerHTML);
}

It’s clear that, as long as existing code doesn’t conflict with the $() function, it’s very easy to start using jQuery in existing projects.