- Introduction
- jQuery Selectors
- jQuery Chaining
- Early 'Page Ready' Event
- jQuery Code Versus X Library Code
- Next Steps
jQuery Code Versus X Library Code
To illustrate the difference between a good first-generation library (X library) and a second-generation library (jQuery), let's rewrite the JavaScript code I used to pretty up an HTML table in my article "Enrich Your HTML Tables with JavaScript Progressive Enhancement." Here's a simplified version of the original code:
function enrichTable(table) { var rows = xGetElementsByTagName("TR",table); var rcnt = 0; // odd-even row count for (var rc = 0; rc < rows.length; rc++) { var row = rows[rc]; rcnt++; xAddClass(row,rcnt % 2 == 0 ? "EvenRow":"OddRow"); if (row.cells.length) { xAddClass(row.cells[0],"FirstColumn"); xAddClass(row.cells[row.cells.length - 1],"LastColumn"); } } } function enrichPrintoutTables() { xGetElementsByClassName("printout",document,"TABLE",enrichTable); } xAddEventListener(window,"load",enrichPrintoutTables);
The code is executed after the document is loaded, finds all tables with the printout class, and sets the row class to EvenRow or OddRow. It also sets the class of the first and the last column in the table (to change the border formatting).
It's very simple to achieve the same effects in jQuery with only six lines of highly readable code:
$(function() { $('TABLE.printout TR:odd').addClass('OddRow'); $('TABLE.printout TR:even').addClass('EvenRow'); $('TABLE.printout TD:first-child').addClass('FirstColumn'); $('TABLE.printout TD:last-child').addClass('LastColumn'); });