Using javascript to check if an HTML table cell is empty?

Is this simple JS code that allows me to check if a cell is empty.

I am trying to encode a function that is called using "onmouseover = func ()"; I just can't get the JS code correctly. Any ideas?

Ideally, which aims to work, this is code that can determine if a cell is empty, and if so, put a simple value, such as "Cell Empty."

I know this probably sounds easy, but I could help a little. Thanks for any ideas.

+7
javascript html
source share
3 answers

It depends a little on what will be there initially. In my experience, tables behave strangely if the cell contains only white space characters, and therefore placing   there to stop its coagulation. Anyway, here is how you can check:

 function elementIsEmpty(el) { return (/^(\s|&nbsp;)*$/.test(el.innerHTML); } function replaceCell(td) { if (elementIsEmpty(td)) { td.innerHTML = 'Cell Empty'; } } <td onmouseover="replaceCell(this)"></td> 

... although the best way would be to apply the behavior through Javascript event handlers.

+3
source share

If you are using jQuery, use the html() method for the element. Given this markup:

 <td id="my_cell"></td> 

This code will do this:

 if ($('#my_cell').html() == '') { $('#my_cell').html('Cell Empty'); } 
+2
source share

Incoming jQuery (as in the good old days):

 function func(e){ var target = window.event ? window.event.srcElement : e ? e.target : null; if (target.innerHTML === ''){ target.innerHTML = 'Cell Empty!'; } } 
+1
source share

All Articles