Inserting a table row at a particular index

Discussion in 'JavaScript' started by cyberpine, Dec 4, 2009.

  1. #1
    Looking to insert a TR when the H: string is found in my table with the string following H:


    In the below example test code, 3 table rows qualify to be displayed, but only one should have a table row header inserted. And that row should be inserted above that row. My attempts to add that code fails so below code does everything except the TR insert which should look like this.


    
    <TR><TD>testing</TD></TR>
    
    Code (markup):
    testing code: no attempt to insert the row is in this code.


    
     <html> 
    <head> 
    </head> 
    <body> 
    <table> 
    <TR><td>test</td></TR> 
    <TR><td>test2</td></TR> 
    <TR><td>test3</td></TR> 
    <TR><td>test4</td></TR> 
    <TR><td>Qualifies1(HP)</td></TR> 
    <TR><td>test</td></TR> 
    <TR><td>test2</td></TR> 
    <TR><td>test3</td></TR> 
    <TR><td>test4</td></TR> 
    <TR><td>Qualifies2(HP)</td></TR> 
    <TR><td>test</td></TR> 
    <TR><td>test2</td></TR> 
    <TR><td>test3</td></TR> 
    <TR><td>QualifiesH(HP)(H:testing)</td></TR> 
    <TR><td>test</td></TR> 
    <TR><td>test2</td></TR> 
    <TR><td>test3</td></TR> 
    </table> 
    </body> 
    </html> 
    <script type="text/javascript"> 
      var theRows = document.getElementsByTagName('TR'); 
      var r = theRows.length; 
      var strTitle, 
          row, 
          cell; 
    
    
      while (r--) { 
        row = theRows[r]; 
        cell = row.cells[0]; 
    
    
          if (cell.innerHTML.indexOf("(HP)") == -1) { 
            row.style.display = "none"; 
          } else { 
            cell.innerHTML = cell.innerHTML.replace("(HP)",""); 
          } 
      } 
    </script>
    
    Code (markup):
     
    Last edited: Dec 4, 2009
    cyberpine, Dec 4, 2009 IP
  2. ajaXpert

    ajaXpert Member

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #2
    Set an id to the table. Then you can add a tr in this way:

    myTable = document.getElementById(tableId);
    var tr = myTable.insertRow(INDEX);

    You can define the index in your while loop as you wish.
     
    ajaXpert, Dec 6, 2009 IP
  3. cyberpine

    cyberpine Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Let me ask you, is it neccessary to do this to a specific table/tableid? I'm asking because the code the generates the table is a black box and really have no way to get the tableid, even from the rendered code.

    Thanks.
     
    cyberpine, Dec 9, 2009 IP