Getting Started With jQuery - The DOM
Written by Ian Elliot   
Monday, 08 October 2012
Article Index
Getting Started With jQuery - The DOM
jQuery Idioms

 

jQuery Idioms

Consider for a moment:

var divs = jQuery('#div1');
var temp=divs.text();
alert(temp);

This gets the DOM object corresponding to the div element with id div1 and stores this as a jQuery object in divs. It then uses the jQuery method text to retrieve the text it contains and displays the text using an alert. Notice the text method will collect all of the text in each of the DOM objects selected but in this case there is only one.

There is nothing wrong with this code snipped but it doesn't look like most jQuery programs. It is more usual to write jQuery using the fluent style of calling methods. So you would write the above as:

var temp=jQuery('#div1').text();
alert(temp);

In general programmers tend to write as many jQuery methods calls as possible, one after another until they reach the final result they want.

jQuery also defines, for reasons that don't really matter much, the dollar symbol as the global jQuery object. That is

var $=jQuery;

and most programmers would write the example as:

var temp=$('#div1').text();
alert(temp);

This makes the code more compact, but it also makes it look more intimidating to the beginner.

But if you remember that whenever you see "$"you simply read "jQuery" it becomes understandable.

There are a few other jQuery idioms that will become apparent as we progress.

justjquery

DOM versus jQuery

In most cases once you have a jQuery object it is best to try to make use of it to get the job done. However, it is always worth remembering that you can make use of the DOM objects directly. Usually this isn't a good idea because jQuery irons out any variations in browser and implementations. If you can do the job in jQuery then it is usually the best approach.

For example, suppose you want to set the text in the div with id div1. The jQuery way is:

$('#div1').text("my new text");

The text method can be used to set text on almost all elements apart from some form element.

It also returns a jQuery object and so allows you to carry on chaining jQuery method calls.It also sets the text on each fo the selected DOM elements in the array.

However if you want to work with the DOM object directly you can. For example, DOM objects have an innerHTML property which corresponds to what it between the tags - in the case of a div what is between the <div> and </div>. So to use the DOM object rather than jQuery you would write:

var temp=$('#div1')[0];
temp.innerHTML='My New Text';

This works but doesn't process the text to remove HTML special characters.

You could have written this as:

$('#div1')[0].innerHTML='My New Text';

and in this form it looks a lot like the jQuery text method vesion - but it isn't.

The whole point is that $('#div1')[0] isn't a jQuery object but a DOM object. Beginners often make the mistake of writing things like:

$('#div1')[0].text('my text');

which doesn't work because DOM objects don't have jQuery methods. 

Always remember that any DOM objects you reference in the array are just that - DOM objects and not jQuery objects.

There is a way to put the previous mistake to rights. You can wrap any DOM object in a jQuery object by writing

$(DOMobject);

So to make the above incorrect example work you would use:

$($('#div1')[0]).text('My New Text');

Now you begin to see how cryptic jQuery expressions become.

Let's break it down.

First we retrive the DOM object:

var DOMobject=$('#div1')[0]);

Next we wrap the DOM object in a jQuery object:

var jQueryObjec=$(DOMobject);

Notice that at this point we are back were we started with a DOMobject that is the first element of an array - I never claimed that this was a sensible thing to do!

Finally we use the text method which sets the text of all of the DOM objects in the array:

jQueryObject.text('My New Text');

Notice that this conversion to DOM object and back to jQuery object can have some practical use. For example if you use jQuery to get all of the divs in the bigdiv class:

var bigdivs=jQuery('.bigdiv');

you can now step through each DOM object in turn, wrapping it in a jQuery object and setting its text to something:

var bigdivs=$('.bigdivs');
for(var i=0;i<bigdivs.length;i++){
 var DOMobject=bigdivs[i];
 var jQueryObject=$(DOMobject);
 jQueryObject.text(i.toString());
}

Which of course can be written in a  more compact form with the jQuery expression on a single line:

var bigdivs=$('.bigdivs');
for(var i=0;i<bigdivs.length;i++){
  
$(bigdivs[i]).text(i.toString());
}

So if you want to step though the DOM objects and do something complicated to them then this is possible and you can re-wrap them in a jQuery object to make it easier.

jQuery Wins

With jQuery you usually find that there is a pure jQuery way to do anything you struggled to do directly with the DOM. In this case the text method accepts a function with the form function(index,oldtext), which is called for each DOM object in the array. The index is the index of the DOM object in the array and the oldtext is its current text content. The string that the function returns is set as the text for the DOM object.

This means that we could write the above without a loop and using nothing but jQuery:

bigdivs.text(function(i,oldtext){
                return i.toString();
});

Never underestimate jQuery!

Summary

  • jQuery is a library that lets you work with the DOM in a browser-independent way.
  • You can use jQuery or $ for the jQuery global object.
  • jQuery selects DOM objects based on CSS selectors.
  • The simplest CSS selectors are tag type, id and class:
    $('name') selects all DOM objects corresponding to <name>
    $('id') selects the single DOM object with id='name'
    $('.name') selects all DOM objects with class='name'
  • The DOM objects are always stored in an array wrapped by jQuery methods and properties - even if there is only one.
  • Most jQuery methods work with all of the DOM objects in the array or just the first.
  • You can get at the DOM objects in the array, e.g. $('div')[i], but you need to remember that they are not jQuery objects.
  • You can wrap any DOM object in a jQuery object using $(DOMobject).

 

Coming Next

So what else is there to learn about jQuery?

You need to learn more sophisticated ways of selecting elements, what methods are available to make changes to elements and so on.

Then of course there are the other areas that jQuery helps with - events, Ajax and the UI.

More in future articles.

 

 

 

  

jquerycover

Chapter List 

  1. The DOM
  2. CSS Selectors
  3. Filters
  4. Advanced Filters
  5. Manipulating The DOM
  6. Promises & Deferred
  7. Promises, Deferred & WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basic -  post
  10. Ajax - Advanced Ajax To The Server 
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding
  15. jQuery - Easy Plugins
  16. jQuery UI
  17. jQuery UI Custom Control - Widget Factory
  18. Getting Started With QUnit Testing

 

 To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin,  or sign up for our weekly newsletter.

 

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

 

Banner


JavaScript Jems - Objects Are Anonymous Singletons

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, every object can be regard [ ... ]



JavaScript Canvas - Typed Arrays

Working with lower level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.


Other Articles

 

 



Last Updated ( Sunday, 19 February 2017 )