0

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?

1 Answer 1

0

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";
            }
        }
    }
}
1
  • Thanks. Is there any library we could use to avoid writing this kind of repetitive code?
    – nicku
    Commented Dec 15, 2022 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.