javascript - Give all child elements classes -
im trying give child elements class per group. each groups children have same class each group, , each element should have different class.
this got far:
var $span = $("tr.keep td"); $span.attr('id', function (index) { return 'td' + index; });
the problem have multiple groups of same parent - script runs trough of them instead repeating class each group. how ad .each on script, or better way?
html:
<tr class="keep"> <tr class="test"> <td rowspan="2"><a href="/"><img src="/" alt=""></a></td> <td colspan="3"><a href="/">text</a></td> </tr> <tr class="test"> <td>mf216n/a</td> <td>apple</td> <td class="outofstock">0</td> <td>1 054,24sek</td> <td><input type="button" class="actionbutton" value="köp" onclick="buy(this, 65360, null, null,null, '/ajax/buy')"></td> </tr> </tr> <tr class="keep"> <tr class="test"> <td rowspan="2"><a href="/"><img src="/" alt=""></a></td> <td colspan="3"><a href="/">text</a></td> </tr> <tr class="test"> <td>mf216n/a</td> <td>apple</td> <td class="outofstock">0</td> <td>1 054,24sek</td> <td><input type="button" class="actionbutton" value="köp" onclick="buy(this, 65360, null, null,null, '/ajax/buy')"></td> </tr> </tr>
use tr.test
selector select tr
elements having class .test
. iterate selected elements using .each
, find td
elements children of selected-tr
elements. loop through td
elements , and add class using .addclass
considering index.
note: tr
elements can not have tr
children. invalid-markup
var $span = $("tr.test"); $span.each(function(i, elem) { $(elem).find('td').each(function(index) { $(this).addclass(function() { return 'td_' + (index + 1); }); }); });
.td_1 { background: yellow; } .td_2 { background: green; } .td_3 { background: pink; } .td_4 { background: orange; } .td_5 { background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr class="keep"> <td rowspan="2"> <a href="/"> <img src="/" alt=""> </a> </td> <td colspan="3"><a href="/">text</a> </td> </tr> <tr class="test"> <td>mf216n/a</td> <td>apple</td> <td class="outofstock">0</td> <td>1 054,24sek</td> <td> <input type="button" class="actionbutton" value="köp" onclick="buy(this, 65360, null, null,null, '/ajax/buy')"> </td> </tr> <tr class="keep"> <td rowspan="2"> <a href="/"> <img src="/" alt=""> </a> </td> <td colspan="3"><a href="/">text</a> </td> </tr> <tr class="test"> <td>mf216n/a</td> <td>apple</td> <td class="outofstock">0</td> <td>1 054,24sek</td> <td> <input type="button" class="actionbutton" value="köp" onclick="buy(this, 65360, null, null,null, '/ajax/buy')"> </td> </tr> </table>
Comments
Post a Comment