0

I have used below jquery code for my bootstrap table

$(document).ready(function() {
    $('.table>tr>td').addClass('redBg');
    console.log('hg');    
});

As well as i tried this one

$(document).ready(function() {
    $('.table>tbody>tr>td').addClass('redBg');
    console.log('hg');

});

But the class will not added to the td tag,

Here is the working fiddle https://jsfiddle.net/udarazz/0vx7tjfq/

Can anyone help me to fix this issue?

7
  • how about $('.table tr > td').addClass('redBg') Commented Aug 15, 2017 at 9:02
  • @N.Ivanov yes it's working, but i need to specify the table. Is there any other way to do that Commented Aug 15, 2017 at 9:02
  • 1
    when using jquery you do not need to use . infront of html defined tags. you can use . only with classnames Commented Aug 15, 2017 at 9:02
  • 1
    @N.Ivanov The table has a class called table, if you look inside the snippet Commented Aug 15, 2017 at 9:04
  • @Udara Try to use $(".table tr:eq(1) > td").addClass("redBg"); Commented Aug 15, 2017 at 9:10

3 Answers 3

2

If you omit it, many browsers will implicitly add a <tbody> container to wrap all table rows. You can verify it by using your browser's developer tools/inspector. The resulting structure:

<table>
    <tbody>
        <tr>
            <td></td>
        </tr>
    </tbody>
</table>

It means <tr> is no longer a direct child of <table>, and your table > tr selector won't work anymore.

To work around it, you can either:

  • Explicitly include <tbody> in your markup and use table > tbody > tr > td selector.
  • Don't use direct child selector: table tr > td

Working JSFiddle.

As Bootstrap styles the backgrounds of even rows and hovers, you might need to make your class definition more specific than Bootstrap's built-in styles:

table.table tr > td.redBg {
    background-color: red;
}

Alternatively, you can add !important to your CSS to override:

.redBg {
    background-color: red !important;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If its the first <td> in the <table> you're trying to add the class to use:

$(document).ready(function() {
  $('.table tr td:first-child').addClass('redBg');
  console.log('hg');
});

https://jsfiddle.net/0vx7tjfq/5/

Comments

0

UPDATED JQUERY

$(document).ready(function() {
    $('.table tr > td').addClass('redBg');
    console.log('hg');
});

1 Comment

Presumably the OP put the descendant selectors there for a reason. Removing them will change the logic for the styles applies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.