Jerry Svensson Jerry Svensson - 6 months ago 27
Javascript Question

Give closest elements class from siblings string

I have a few tr elements that are divided by a category header - I want to add the class from the a elements string to the tr class below and to repeat this trough out. the .keep elements can vary in amount.

How do I do this the best way?

<tr>
<td class="unfoldedlabel" colspan="6”>
<a href="">Drives</a
</td>
</tr>

<tr class="keep”> - should add class .drives
</tr>

<tr class="keep”> - should add class .drives
</tr>

<tr>
<td class="unfoldedlabel" colspan="6”>
<a href=“">Memory</a
</td>
</tr>

<tr class="keep”> - should add class .memory
</tr>

<tr class="keep”> - should add class .memory
</tr>

Answer

Try this:

var title = "";
$( "table tr" ).each(function( index ) {
    if($(this).find("a").length == 1) {
        title = $(this).find("td").find("a").text();
    } else {
        $(this).addClass(title.toLowerCase());
    }
});