You know, the more I use it, the more I’m absolutely loving jQuery, and am wondering what took me so long to adopt it. Let me show you what I mean. Here’s some sample code that is done without jQuery; in other words, normal javascript:
var panel = document.getElementById(panelid);
for (var i = 0; i < panel.childNodes.length; i++){
var ctrl = panel.childNodes[i];
if (ctrl.className.indexOf('cancel') >= 0){
if (window.attachEvent)
ctrl.attachEvent('onclick', cancel_click);
else if (window.addEventListener)
ctrl.addEventListener('click', cancel_click, false);
}
}
Pretty normal looking code. Now, I can do the same thing with a single line of code in jQuery:
$('#' + panelID).find('.cancel').click(cancel_click);
Now, that’s cool! What’s going on here? I’ll break it down for you.
- First, I need to locate the control that represents my parent panel. jQuery uses CSS type accessors. In CSS, if you want to style an element based on it's ID, you use #, followed by the id of the element. The $ function locates the element or set of elements with the given id.
- Next, the find method searches all descendent controls of the panel, and returns all controls who have a class of ‘cancel’. Remember, we’re using CSS selectors here, thus the dot.
- Finally, I attach a click handler to the element (a button in the code I derived this sample from).
If you haven’t browsed in to jQuery yet, do yourself a favor and check it out! It makes doing mundane stuff in javascript mostly a thing of the past.