How to highlight alternate table row using jQuery ?
In this article, we will set the highlight on an alternative table row using jQuery. The :nth-child(2n) selector is used to select the alternative row and addClass() method is used to set the style the alternative rows.
Syntax:
$(tr:nth-child(2n)").addClass("GFG");
Here, we will create a simple table using <table> tag. The <thead> and <tbody> tags are used to create heading and body elements of table. We use some CSS properties to set the styles.
Example:
HTML
<!DOCTYPE html> < html > < head > < title > How to highlight alternate table row using jQuery? </ title > < script src = </ script > < style > table { margin: 0 auto; } tr, th, td { border: 2px solid black; padding: 20px 50px; } th { background-color: green; } .GFG { background: rgb(145, 145, 145); } </ style > < script > $(document).ready(function () { $("table tbody tr:nth-child(2n)").addClass("GFG"); }); </ script > </ head > < body style = "text-align: center;" > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < h3 > How to highlight alternate table row using jQuery? </ h3 > < table > < thead > < tr > < th >Sl.No</ th > < th >Title</ th > < th >Geek_id</ th > </ tr > </ thead > < tbody > < tr > < td >01</ td > < td >HTML</ td > < td >Markup Language</ td > </ tr > < tr > < td >02</ td > < td >CSS</ td > < td >Cascading Style</ td > </ tr > < tr > < td >03</ td > < td >JavaScript</ td > < td >Scripting Language</ td > </ tr > < tr > < td >04</ td > < td >Bootstrap</ td > < td >Framework</ td > </ tr > </ tbody > </ table > </ body > </ html > |
Output: