You are missing the whole point of jQuery. Your preferred method doesn't work with jQuery because jQuery doesn't operate on single DOM elements. A single DOM element has an onclick property, so if you did something like this it would work:
document.getElementById('bar').onclick = function() { // blah };
However, jQuery is all about sets. For example, in the code you pasted, you are trying to bind something to all elements with a class of foo
. When doing stuff like this, you have to play by jQuery's rules (and this is a Good Thing!). A wrapped set, ie, $('.foo')
is not the same as directly getting a DOM element like I did above. It will, however, contain an array of all the DOM elements found, which jQuery exposes. So if there was a single element with a class of foo
in the document, you could do:
$('.foo')[0].onclick = function() { // blah };
This is, however, not recommended as the whole point of jQuery is to abstract out all this specific Javascript syntax and let jQuery figure things out for you. You should embrace this, as it will make your code much cleaner and portable. As such, you should use the click
or the bind
functions:
$('.foo').click(function() {
// will bind something to all elements with a class of foo
});
$('.foo').bind('click', function() {
// functionally identical to the above, either is fine
});