Home > Net >  Failed to mark every empty cell as Empty Cell with JQuery or Javascript
Failed to mark every empty cell as Empty Cell with JQuery or Javascript

Time:08-29

I searched for solutions to this but still I failed to replace each empty cell with the sentence "empty cell" with JQuery or Javascript, knowing that this technique only works if I give the cell its id <td id=#cell"> for instance. You can see below that I've tried it with both Javascript and JQuery but with no results at all, I don't wish to use ids or classes for this matter, I wish to select all cells (< td >) that are empty, all at once, and then replace their value with "empty cell".
Please help.

Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page title</title>
<style>
table, th, td { border: 1px solid black; } th { cursor: pointer; }
</style>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
        <tr><th>id</th><th>name</th><th>age</th></tr>
        <tr><td>1</td><td>Julian</td><td>31</td></tr>
        <tr><td></td><td>B</td><td></td></tr>
        <tr><td>3</td><td></td><td>25</td></tr>
        <tr><td>4</td><td>Mindy</td><td>32</td></tr>
        <tr><td>5</td><td id="dud"></td><td>40</td></tr>
    </table>
<script>
if ($("td").html() == '') {
  $("td").html('Cell Empty');
}


if ($("#dud").html() == '') {
  $("#dud").html('Cell Empty');
}


const lis = document.getElementsByTagName("tr");
if(lis.length === 0){
lis.innerHTML = "New text!";
}
</script>
</body>
</html>

CodePudding user response:

You can use this

const tdArr = Array.from(document.querySelectorAll('td')).filter(td => td.innerText == '')

for(const td of tdArr) td.innerText = "empty cell"

QuerySelectorAll will select all of the td and then converting it to array by using array.from and then filtering the array by only putting those td whose innerText is empty.

If you only want to change the content you can do it directly by the below code

Array.from(document.querySelectorAll('td')).forEach(td => if(td.innerText == '') td.innerText = 'empty cell'
}
   

Hope this helps!!

  • Related