Add css for odd lines having a specific class with jQuery

I have the following markup

<tr>
  <td>1,1</td>
</tr>
 <tr>
  <td>2,1</td>
</tr>
<tr class="add-css">
  <td>3,1</td>
</tr>

And I want to add background color for odd lines that have add-css class, My ruff jQuery code

$( "tr" ).filter( ":odd" )hasClass('add-css').css( "background-color", "blue" );
+4
source share
2 answers

You missed the point .for hasClassand hasClassreturn boolean, so further binding will not be possible if a jQuery object is required. You can use a class selector with a type selector.

. hasClass ()

The .hasClass () method will return true if a class is assigned.

The .hasClass () method will return true if a class is assigned to an element, even if other classes are also

$( "tr.add-css" ).filter( ":odd" ).css( "background-color", "blue");

OR

$( "tr.add-css:odd" ).css( "background-color", "blue");
+6
source

You can try this

$( "tr:nth-child(odd)" ).each(function(index, element) {

    if($(this).hasClass('add-css')){
        $(this).css( "background-color", "blue" );
    }
});

or even you can do it with css using

tr.add-css:nth-child(odd){
    background-color:blue;
}
+1

All Articles