最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide specific row from table without ID - Stack Overflow

programmeradmin1浏览0评论

I have simple table generated by PHP.

<table border="1" id="control>
    <tbody>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>  //Row #3
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

I would like to hide 3rd row when page loads using javascript or css. Is there any way to do this without giving 3rd row ID?

Thank you in advance

I have simple table generated by PHP.

<table border="1" id="control>
    <tbody>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>  //Row #3
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

I would like to hide 3rd row when page loads using javascript or css. Is there any way to do this without giving 3rd row ID?

Thank you in advance

Share Improve this question asked Oct 26, 2013 at 14:08 hackalhackal 153 silver badges8 bronze badges 1
  • The JavaScript answers here are using .getElementsByTagName(). The idiomatic means of accessing table rows by index is to use the native collections that are specific to table rows and cells. For example: document.getElementById("#control").rows[2].style.display = "none"; – Blue Skies Commented Oct 26, 2013 at 14:38
Add a ment  | 

5 Answers 5

Reset to default 5

with css3 you can use the :nth-child selector

#control tr:nth-child(3)
{
   display:none;
}

using jquery its pretty simple, $('#control tr:eq(2)').hide()

Try this

 document.getElementsByTagName("tr")[2].style.display = 'none';

Using pure JavaScript (no framework like JQuery etc.) one can do:

<!DOCTYPE html>
<html>
<head>
    <title>HTML</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <table border="1" id="control">
        <tbody>
            <tr><td>row1</td></tr>
            <tr><td>row2</td></tr>
            <tr><td>row3</td></tr>
            <tr><td>row4</td></tr>
            <tr><td>row5</td></tr>
            <tr><td>row6</td></tr>
        </tbody>
    </table>
    <script type="text/javascript">
        var tableElm = document.getElementById("control");
        var tableChilds = tableElm.getElementsByTagName("tr");
        var row3 = tableChilds[2];
        row3.style.display = "none";
        // alternatively:
        //row3.style.visibility = "hidden";
    </script>
</body>
</html>

Use jQuery's eq(int) to select the row at the zero-based index:

$("#control tr").eq(2).hide();
发布评论

评论列表(0)

  1. 暂无评论