Well, one way to do this is to simply put the class in the “parent” rows and remove all ids and inline onclick ids:
<table id="products"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Destination</th> <th>Updated on</th> </tr> </thead> <tbody> <tr class="parent"> <td>Oranges</td> <td>100</td> <td><a href="#">+ On Store</a></td> <td>22/10</td> </tr> <tr> <td></td> <td>120</td> <td>City 1</td> <td>22/10</td> </tr> <tr> <td></td> <td>140</td> <td>City 2</td> <td>22/10</td> </tr> ...etc. </tbody> </table>
And then you have CSS that hides all non-parents:
tbody tr { display : none; // default is hidden } tr.parent { display : table-row; // parents are shown } tr.open { display : table-row; // class to be given to "open" child rows }
This greatly simplifies your html. Note that I added <thead> and <tbody> to your markup to make it easier to hide data lines and ignore header lines.
With jQuery, you can simply do this:
// when an anchor in the table is clicked $("#products").on("click","a",function(e) { // prevent default behaviour e.preventDefault(); // find all the following TR elements up to the next "parent" // and toggle their "open" class $(this).closest("tr").nextUntil(".parent").toggleClass("open"); });
Demo: http://jsfiddle.net/CBLWS/1/
Or, to implement something like this in plain JavaScript, maybe something like the following:
document.getElementById("products").addEventListener("click", function(e) { // if clicked item is an anchor if (e.target.tagName === "A") { e.preventDefault(); // get reference to anchor parent TR var row = e.target.parentNode.parentNode; // loop through all of the following TRs until the next parent is found while ((row = nextTr(row)) && !/\bparent\b/.test(row.className)) toggle_it(row); } }); function nextTr(row) { // find next sibling that is an element (skip text nodes, etc.) while ((row = row.nextSibling) && row.nodeType != 1); return row; } function toggle_it(item){ if (/\bopen\b/.test(item.className)) // if item already has the class item.className = item.className.replace(/\bopen\b/," "); // remove it else // otherwise item.className += " open"; // add it }
Demo: http://jsfiddle.net/CBLWS/
In any case, put JavaScript in the <script> element, which is located at the end of the body, so that it runs after the table has been parsed.
nnnnnn Nov 05 '13 at 20:19 2013-11-05 20:19
source share