Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add css for odd rows having particular class with jQuery

Tags:

html

jquery

css

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 the odd rows which have class add-css, My ruff jQuery code is

$( "tr" ).filter( ":odd" )hasClass('add-css').css( "background-color", "blue" );
like image 608
web dev Avatar asked Mar 15 '23 18:03

web dev


2 Answers

You missed the dot . for hasClass and hasClass return boolean value, so further chaining wont be possible that require the jQuery object. You can use class selector with the type selector.

.hasClass()

The .hasClass() method will return true if the class is assigned to an element

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

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

OR

$( "tr.add-css:odd" ).css( "background-color", "blue");
like image 54
Adil Avatar answered Apr 03 '23 18:04

Adil


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;
}
like image 34
Ajay Chaudhary Avatar answered Apr 03 '23 16:04

Ajay Chaudhary