looping through table rows

Discussion in 'JavaScript' started by merlin6b, Jun 18, 2008.

  1. #1
    - I have table rows (TR).

    The special Row:
    - One table row is special, and has the class name: container in first child (TD).
    - The second child in special row, the IMG tag act as click listener.

    The goal:
    - If someone click on special row second child, the IMG tag, I want to hide all row (except the special row) until next container (special row) appear.

    Example: Someone click on IMG tag in line 3:. I want to hide each table row between 5: and 16: (except the special row 2: and 4: )

    1: <tbody> 
    2:    <tr id="forum-list-1"> 
    3:       <td colspan="4" class="container"><img src="img.gif" alt="[img]" />Click here</img></div></td> 
    4:    </tr> 
    5:    <tr id="forum-list-3"> 
    6:       <td>forum1</td> 
    7:       <td>0</td> 
    8:       <td>0</td> 
    9:       <td>na</td> 
    10:    </tr> 
    11:   <tr id="forum-list-4"> 
    12:      <td>forum2</td> 
    13:      <td>0</td> 
    14:      <td>0</td> 
    15:      <td>na</td> 
    16:   </tr> 
    17:   
    18:   <tr id="forum-list-2"> 
    19:      <td colspan="4" class="container"><img src="img.gif" alt="[img]" />Click here</img></td> 
    20:   </tr> 
    21:   <tr id="forum-list-5"> 
    22:      <td>forum3</td> 
    23:      <td>0</td> 
    24:      <td>0</td> 
    25:      <td>na</td> 
    26:   </tr> 
    27: </tbody>
    Code (markup):
    I achieve this using a for loop.

    
    var containerRow = document.getElementById('forum-list-1');
    
    for (var el = containerRow.nextSibling; el; el = el.nextSibling)
    {
    	if (el.nodeType == 1) 
    	{
    		if (el.cells[0].className == "container")
    		{
    			break;
    		}
    				
    		if (!Core.hasClass(el, "hide"))
    		{
                   		Core.addClass(el, "hide");
    		}
    		else
    		{
    			Core.removeClass(el, "hide");
    		}
    	}
    }
    Code (markup):
    Someone tell me is easier to solve this problem using a "while" loop. Is true ? And my code is correct or exist a simpler and more beautiful way to achieve this ?

    Thanks!
     
    merlin6b, Jun 18, 2008 IP