Basic understanding of API — table.$('td').addClass('tablecell');

Basic understanding of API — table.$('td').addClass('tablecell');

george.levinesgeorge.levines Posts: 11Questions: 4Answers: 0

Can someone explain why the second to last line here does not add a class of 'tablecell' to all my <td> elements?

$(document).ready(function() {
    var table = $('#ratings-table').DataTable({
        "ajax": 'table_senate_info.json',
        "columns": [
            { "data": "ratingPhrase" },
            { "data": "state" },
            { "data": "fullName" },
            { "data": "trump_margin" },
            { "data": "firstName" },
            { "data": "lastName" },
            { "data": "raceRatingID" },
            { "data": "open_seat" }
        ],
        "columnDefs": [
            { targets: [4, 5, 6, 7], visible: false },
            {
                "targets": 2,
                "render": function(data, type, row) {
                    return data + ' (' + row.open_seat + ')';
                }
            },
            { "orderData": 5, "targets": 2 },
            { "orderData": [6, 5], "targets": 0 }
        ],
        renderer: "bootstrap",
        responsive: "true",
    });
    table.$('td').addClass('tablecell');
});

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 4,693Questions: 0Answers: 823

    Hi @george.levines ,

    Because it's not a valid method. You could just use $('td').addClass('tablecell');

    Cheers,

    Colin

  • george.levinesgeorge.levines Posts: 11Questions: 4Answers: 0

    So that doesn't seem to do anything either.

    FWIW I thought my original followed this.

  • colincolin Posts: 4,693Questions: 0Answers: 823

    Ah, you are right, it does work! My apologies.

    Yep, see here - it's definitely adding the class to my cells.

    C

  • allanallan Posts: 49,501Questions: 1Answers: 7,286 Site admin
    Answer ✓

    Its because the table in the original post is loaded with the ajax option. So the loading of the data is async. The code to add a class is running before the data is loaded (and thus any table cells drawn)!

    Use either initComplete to run code after the data has been loaded, or use createdRow or columns.createdCell on a per row or cell basis.

    Allan

  • george.levinesgeorge.levines Posts: 11Questions: 4Answers: 0

    Thanks for the answer.

    Follow-up question given the original code ...

    If I wanted to say if data in open_seat is equal to 1 change the fullName cell in that same row blue, how might I go about doing that? And what's the documentation that would answer that question?

  • kthorngrenkthorngren Posts: 5,543Questions: 19Answers: 1,233
    edited January 24

    You would use either createdRow or rowCallback if the data can change. Both have examples.

    Something like table.$('td').addClass('fred'); wouldn't have an option to make the setting based on the data.

    Kevin

Sign In or Register to comment.