Two very useful selecm selectors in the jQuery library are: oddand: even. Let's take a look at how we can use one of them for basic table striping, given the following tables:
tr {background-color: #fff;}.alt {background-color: #ccc; }
Finally, we write our jQuery code, attaching the class to the odd-numbered table rows (<tr> tags ):
$(document).ready(function() {$('tr:even').addClass('alt');});
Now we add a style that affects all the rows in the style table, and then use the alt class to affect all the even rows:
Finally, we write the next jquery code to bind this class to all the even rows of the table (<tr> label)But wait! Why use the: evenselector for odd-numbered rows? Well, just as with the: eq () selector, the: evenand: oddselectors use JavaScript's native zero-based numbering. therefore, the first row counts as 0 (even) and the second row counts as 1 (odd), and so on. with this in mind, we can perform CT our simple bit of code to produce tables that look similar to the following screenshot:
$(document).ready(function() {$('tr:nth-child(odd)').addClass('alt');});
As before, note that: nth-child () is the only jQuery selector that is one-based. to achieve the same row striping as we did above-limits T with consistent behavior for the second table-we need to use oddrather than evenas the argument. with this selector in place, both tables are now striped nicely, as shown in the following screenshot:
$(document).ready(function() {$('tr:nth-child(odd)').addClass('alt');$('td:contains(Henry)').addClass('highlight');});
So, now we can see our lovely striped table with the Henryplays prominently featured:
Admittedly, there are ways to achieve the row striping and text highlighting without jQuery-or any client-side programming, for that matter. nevertheless, jQuery, along with CSS, is a great alternative for this type of styling in cases where the content is generated dynamically and we don't have access to either the HTML or server-side code.
Note that the contains () selector is case sensitive and uses $ ("td: contains (henry)") instead of uppercase H, no element is selected. It is true that there are many ways to add strip and text highlighting to a table without jquery-or any browser programming. However, using jquery and css is a particularly good option to implement such type of modification, especially when the content is dynamically added and we cannot access html or server-side code.