If I had two html tables like so:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Total</th>
<th>Discount</th>
<th>Difference</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Peter</td>
<td>Parker</td>
<td>28</td>
<td>$9.99</td>
<td>20.9%</td>
<td>+12.1</td>
<td>Jul 6, 2006 8:14 AM</td>
</tr>
<tr>
<td>John</td>
<td>Hood</td>
<td>33</td>
<td>$19.99</td>
<td>25%</td>
<td>+12</td>
<td>Dec 10, 2002 5:14 AM</td>
</tr>
</tbody>
</table>
<br/><br/>
<table id="anotherTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>High Score</th>
<th>Total Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>Clark</td>
<td>Kent</td>
<td>18</td>
<td>32</td>
</tr>
<tr>
<td>Bruce</td>
<td>Almighty</td>
<td>45</td>
<td>180</td>
</tr>
</tbody>
</table>
jQuery on my HTML page:
$(document).ready(function(){
$("#myTable").myplugin();
});
I am creating a jQuery plugin which I want to be able to apply to any or all HTML tables on a page in my application with either $(“table”).myplugin() or $(“#myTable”).myplugin().
in my plugin code:
return this.each(function(index){
// code here
});
If I add the line $(this).addClass('myClass') the CSS “myClass” is added to table “myTable” but if I add the line $('thead').addClass() “myClass” is added to both theads. I’ve tried $(this thead).addClass(), $(this 'thead').addClass(), $('this thead').addClass() but the all throw a JS error. How do I utilize “this” to select only the thead in element “myplugin” is being applied to in this case “myTable”?
You could use the
.findmethod[jQuery docs].If you are certain that
theadis an immediate child ofthis, you can use.childreninstead and it would be faster, especially if you have very large tables.You could also set
thisas the context for your query: