简体   繁体   中英

I need to check if any <td> in a html table is empty/null as in after the page loads it only returns <td></td> and change it to <td><p>$0</p></td>

example of the table

        <table class="tg">
            <thead>
                <tr>
                    <th class="tg-0lax" id="blank-spaces"></th>
                    <th class="titles" id="this">????</th>
                    <th class="titles">???<br></th>
                    <th class="titles">???</th>
                    <th class="titles">???</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                   <td></td>
                   <td>not empty do nothing</td>
                   <td></td>
                </tr>
            </tbody>
        <table>

Now the way this is really written, data will be pushed into each td from an API, some times that API is down, and I would like to use jquery to check if a td has anything displaying in it and if it doesnt I want there to be a string with an error message in the td. This is the jquery im trying currently

var empty = $("td").trim().filter(function () { return this.value.trim() === null })
empty.addClass("errorDefault");

if ($("td").hasClass("errorDefault")) {
    this.val("$0");
    this.text("$0");
    this.html("<p>There was an error getting data</p>");
}
  • There is no.trim() in jQuery
  • string trim() is not going to return null.
  • table cells do not have value
  • $("td").hasClass("errorDefault") only looks at first element

 $("tbody td").filter((_, td) =>.td.textContent.trim().length).addClass("errorDefault");text("$0");
 .errorDefault { background-color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="tg"> <thead> <tr> <th class="tg-0lax" id="blank-spaces"></th> <th class="titles" id="this">????</th> <th class="titles">???<br></th> <th class="titles">???</th> <th class="titles">???</th> </tr> </thead> <tbody> <tr> <td></td> <td>not empty do nothing</td> <td></td> </tr> </tbody> <table>

If it is truly empty, CSS can do it.

 tbody td:empty{ background: red; } tbody td:empty:after { content: "$0"; }
 <table class="tg"> <thead> <tr> <th class="tg-0lax" id="blank-spaces"></th> <th class="titles" id="this">????</th> <th class="titles">???<br></th> <th class="titles">???</th> <th class="titles">???</th> </tr> </thead> <tbody> <tr> <td></td> <td>not empty do nothing</td> <td></td> </tr> </tbody> <table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM