views:

23

answers:

1

Ok, I am using insertRow to insert a TR element into a table, but for some reason it doesn't count that inserted TR element as a sibling of the others when I do nextSibling on it.

For example, consider the following table.

<table id="myTable">
    <tr id="row_0">
        <td colspan="3">Row 1</td>
    </tr>
    <tr id="tr_0_0">
        <td>Option 1</td>
        <td>Option2</td>
        <td>Option 3</td>
    </tr>
    <tr id="tr_0_1">
        <td>Option 1</td>
        <td>Option 2</td>
        <td>Option 3</td>
    </tr>
</table>

So after I do this:

var lTable = document.getElementById("myTable");
var trEle = lTable.insertRow(-1);
trEle.id = "tr_0_2";

var cell1 = trEle.insertCell(0);
cell1.innerHTML = "Option 1";

var cell2 = trEle.insertCell(1);
cell2.innerHTML = "Option 2";

var cell3 = trEle.insertCell(-1);
cell3.innerHTML = "Option 3";

Then I use this approach to get all of the siblings, but it NEVER gives me the last sibling in here, but ONLY if it's been added via insertRow, because it gets all nextSiblings just fine, but once I add a sibling via insertRow it never gives me that last Sibling, argggg....

var tempTr = document.getElementById("row_0");
var totalSibs = 0;

while(tempTr.nextSibling != null)
{

    var tempId = tempTr.id;

    // If no id, not an element, or not a tr_0 id.
    if (!tempId || tempTr.nodeType != 1 || tempId.indexOf("tr_0") != 0)
    {
        tempTr = tempTr.nextSibling;
        continue;
    }

    // This NEVER ALERTS the last id of the row that was inserted using insertRow, arggg.
    alert(tempId);

    totalSibs++;

    tempTr = tempTr.nextSibling;
}

So, totalSibs should return 3 because after I inserted the row, there should be 3 Siblings, but instead returns 2 and never counts the 3rd Sibling.... arggg.

Can someone please help me here??

Thank You, you guys/gals are Awesome!

A: 

The problem is at the last iteration, you set the tempTr to the next sibling, (which is actually the last tr), but you check the again the nextSibling in your while condition, in that last case it will be null, finishing the loop.

Change your while condition to:

while (tempTr != null) {
  //...
}

Or simply:

while (tempTr) {
  //...
}

Try your code here.

CMS
OMG, You're a GENIUS, THANK YOU! :)
SoLoGHoST