简体   繁体   中英

Make table data collapsible

I am trying to make each heading part which is a table collapsible. The user should be able to click on the heading and view the table and click again to hide it. Something as simple as possible. I found something here: https://www.w3schools.com/howto/howto_js_collapsible.asp that seems like a lot of coding for such a simple thing. Is there a simple way to do it in HTML? I am using it in Thymeleaf as part of spring boot, so if it's done in HTML it should be easily doable in Thymeleaf too. Following is the sample HTML that I am using.

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>

    <h1> Concepts only in L1</h1>
    <table>
        <tr>
            <th>missing-con</th>
            <th>parent-con</th>
        </tr>
        <tr>
            <td>{missing-con}</td>
            <td>{parent-con}</td>
        </tr>

    </table>
    <h1> Concepts only in M1</h1>
    <table>
        <tr>
            <th>missing-con</th>
            <th>parent-con</th>
        </tr>
        <td>{missing-con}</td>
            <td>{parent-con}</td>
            <td>{missing-con}</td>
            <td>{parent-con}</td>
</table>
</body>

</html>  

And I am looking to collapse each table. Any suggestions?

Here is one aproach you can addapt your way. I would advise you to add an ID/class name to the table element so you can reference it better. In this example I'm considering the first table on the document. You can also use getElementById or getelementByClassName

var table = document.getElementsByTagName("table")[0];
var th = table.getElementsByTagName("th");
for (var i = 0; i < th.length; i++) {
    th[i].onclick = function() {
        var td = this.parentNode.parentNode.getElementsByTagName("td");
        for (var j = 0; j < td.length; j++) {
            if (td[j].style.display == "none") {
                td[j].style.display = "";
            } else {
                td[j].style.display = "none";
            }
        }
    }
}

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