How can I set td height to 0px in a table?

I have an HTML table that contains multiple rows (it is built dynamically). All <tr>

have one <td>

inside.

If one <td>

does not contain HTML content inside, I would like it to be invisible.

How can I do that? (Not that the HTML inside is rendered dynamically, and I don't want to use display:none

either any other property in <td>

or <tr>

).

Sample code:

<html>
    <body bgcolor="#E6E6FA">
        <table cellSpacing="0" cellPadding="0">
            <tr>
                <td>one cell</td>
            </tr>
            <tr>
                <td bgcolor="#FF0000"></td>
            </tr>
            <tr>
                <td>two cell</td>
            </tr>
        </table>
    </body>
</html>

      

In Firefox, an empty TD is invisible. However, in IE, TD is 1 pixel high:

enter image description here

Looking with the DOM Inspector I can see that it takes up 1 pixel:

enter image description here

How can I make TD not visible? Any scripts I can execute inside TD?

+3


source to share


2 answers


You can use a CSS pseudo selector :empty

:

#myDynamicTable td:empty
{
  display: none;
}

      

JsFiddle example: http://jsfiddle.net/vKEBY/6/



And if you want to support IE <9:

var ieVer = getInternetExplorerVersion();
if (ieVer != -1 && ieVer < 9.0) {
    // for IE<9 support
    var dynamicTable = document.getElementById("myDynamicTable");
    var TDs = dynamicTable.getElementsByTagName("td");

    for (var i = 0; i < TDs.length; i++) {
        if (TDs[i].innerHTML == "") {
            TDs[i].style.display = "none";
        }
    }
}

/**
  * All credits to Microsoft
  * http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx#ParsingUA
  */
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) rv = parseFloat(RegExp.$1);
    }
    return rv;
}โ€‹

      

JsFiddle example: http://jsfiddle.net/vKEBY/6/



+1


source


If using jQuery this script can get much cleaner (just a thought).



$('#myTable td:empty').hide();

      

0


source







All Articles