Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

dom - using javascript's .insertBefore to insert item as last child

I so miss jQuery. I'm working on a project where I need to get my hands dirty with good 'ol plain Javascript again.

I have this scenario:

parent
    child1
    child2
    child3

Via javascript, I want to be able to insert a new node before or after any of those children. While javascript has an insertBefore, there is no insertAfter.

Insert before would work fine on the above to insert a node before any one of those:

parent.insertBefore(newNode, child3)

But how does one insert a node AFTER child3? I'm using this at the moment:

for (i=0,i<myNodes.length,i++){
    myParent.insertBefore(newNode, myNodes[i+1])
}

That is inserting my newNode before the next sibling node of each of my nodes (meaning it's putting it after each node).

When it gets to the last node, myNodes[i+1] become undefined as I'm now trying to access a array index that doesn't exist.

I'd think that'd error out, but it seems to work fine in that in that situation, my node is indeed inserted after the last node.

But is that proper? I'm testing it now in a few modern browsers with no seemingly ill effects. Is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pure JavaScript actually has a method for what you want:

parent.appendChild(child_to_be_last)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...