SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru quenting's Avatar
    Join Date
    Dec 2002
    Location
    Switzerland
    Posts
    735
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    dynamically replace table contents

    ok basically i want to move two rows in a table.
    for example i have the table:

    1 name1 address1
    2 name2 address2
    3 name3 address3
    4 name4 address4


    and i'd like a javascript function to which i could pass a line number, a destination number, and it would then reorganize the table accordingly.
    example: rebuildtable(4,2) would result in:

    1 name1 address1
    4 name4 address4
    2 name2 address2
    3 name3 address3

    and rebuildtable(1,4) in:

    2 name2 address2
    3 name3 address3
    4 name4 address4
    1 name1 address1

    I have tried a method using innerHTML, I seem to be able to access <tr>s' innerhtml (if i do an alert on them i can see their current status), however when i want to replace one tr with some other html it fails for some reason.

    Any way i can do this ? Maybe a simpler solution ?
    Thanks
    The largest message boards on the web !
    unblog.fr, hosting 700000 french blogs

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's quite an example: it appears your rebuildtable() function is random.

    1)In any case, when you are dealing with the elements of a table, your table has to be properly structured--it can't be the sloppy html that most people use for tables. At a minimum, your table has to have a <tbody> element.

    2) Get a reference to the <tbody> element using:

    var tbody = document.getElementById("your_tbody_ID");

    3) Get a reference to the rows array of the <table> using:

    var rows = document.getElementById("your_table_ID").rows;

    4) You can use the tbody reference to remove rows from your table:

    var a = tbody.removeChild(rows[0]);

    removeChild returns a reference to the removed row. After you remove a row, all the rows shift over in the rows array, so if your table had 3 rows, e.g. with index positions 0, 1, 2, you can't then refer to rows[2]. Since you removed a row, there are only rows 0, 1 left.

    5)Use the insertBefore() method to insert rows into your table:

    tbody.insertBefore(a, rows[0]);

    The first argument is the row you want to insert(note: it is the removed row from above), and the second argument is the row you want to insert before.

    Or, you can use appendChild() to add rows to the end of <tbody>:

    tbody.appendChild(a);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •