Search code examples
jqueryhtmlcssjquery-selectorscss-selectors

:empty selector on tbody tag


Given the following table:

<table id="incidents">
    <thead>
        <tr>
            <th></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

Using jQuery the following evaluate as false:

$("#incidents tbody").is(":empty")

I would like to use CSS to set the content to be a message:

#incidents tbody:empty {
    content: "<tr>message foo</tr>";
}

Can the :empty selector be applied to tbody?


Solution

  • No, unfortunately the indentation and newlines within tbody prevent it from ever matching :empty in this case. This applies both to CSS and jQuery, where as far as I know :empty behaves identically, as well as jQuery's :parent, which is equivalent to :not(:empty) (with a very poor choice of name).

    Furthermore, you cannot use CSS content to add elements to the DOM. You'll need to do this in jQuery or the server side: check if tbody has any rows and if not, add that row.

    If you go with jQuery, you can use this:

    var tbody = $("#incidents tbody");
    
    if (tbody.children().length == 0) {
        tbody.html("<tr>message foo</tr>");
    }