开发者

nextSibling issue, should be simple

Ok, I'm trying to come to grips with this nextSibling function in JS. Here's my issue within the following code...

var fromRow = document.getElementById("row_1");

while(fromRow.nodeType == 1 && fromRow.nextSibling != null)
{
    var fRowId = fromRow.id;
    if (!fRowId) continue;

    // THIS ONLY gets done once and alerts "row_1" ONLY :(
    alert(fRowId);

    fromRow = fromRow.nextSibling;
}

Ok can someone please tell me what is wrong with this code? There are siblings next to this document.getElementById("row_1"); element for sure as I can see them, and they all have id attributes, so why is it not getting the id attributes of the siblings?? I don't get it.

row_1 is a TR element, and I need to get the TR elements next to i开发者_如何学编程t within this table, but for some reason, it only gets the 1 element that I can already get using document.getElementById, arggg.

Thanks guys :)


Try:

var fromRow = document.getElementById("row_1");

while(fromRow !== null)
{
    var fRowId = fromRow.id;
    if (!fRowId || fromRow.nodeType != 1) {
        fromRow = fromRow.nextSibling;
        continue;
    }

    // THIS ONLY gets done once and alerts "row_1" ONLY :(
    alert(fRowId);
    fromRow = fromRow.nextSibling;
}

While fromRow.nextSibling != null would halt on the second to last iteration because you already set fromRow to its nextSibling at the end. Also, you don't necessarily want to halt if the next node isn't an element, you just want to move onto the next one if possible. Finally, if you hit the continue in your original example, you'll run into an endless loop because fromRow would never change value.


Your while loop stops as soon as it encounters a node not of type 1. So if there is any whitespace between your elements the while loop will break after the first element.

What you probably want is:

while(fromRow.nextSibling != null)
{
    if(fromRow.nodeType == 1) {
        ...
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜