使用javascript的.insertBefore插入项作为最后一个孩子 [英] using javascript's .insertBefore to insert item as last child
问题描述
我有这种情况:
父
child1
child2
child3
通过javascript,我想要能够在任何这些孩子之前或之后插入一个新节点。虽然javascript有一个 insertBefore
,但是没有 insertAfter
。
之前插入之前可以正常工作,在任何一个之前插入一个节点:
parent.insertBefore(newNode,child3)
但是如何插入节点AFTER child3?我正在使用这个:
for(i = 0,i< myNodes.length,i ++){
myParent.insertBefore(newNode,myNodes [i + 1])$ b $ b}
在我的每个节点的下一个兄弟节点之前插入我的newNode(意思是将其放在每个节点之后)。
当它到达最后一个节点时, myNodes [i + 1]
成为 undefined
,因为我正在尝试访问不存在的数组索引。 p>
我认为这样会出错,但是在这种情况下,我的节点确实插入到最后一个节点之后似乎工作正常。
但这是正确的吗?我现在在几个现代浏览器中测试,没有看似不好的影响。有没有更好的方法?
insertBefore(newNode,referenceNode)$ c的功能$ c>描述为:
将引用节点之前的指定节点插入当前节点的子节点。如果
referenceNode
为null,则newNode
插入到子节点列表的末尾。
由于 myNodes [i + 1]
不在数组边界之外,它返回 undefined
,在这种情况下被视为 null
。这意味着你得到你想要的行为。
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?
The functionality of insertBefore(newNode, referenceNode)
is described as:
Inserts the specified node before a reference node as a child of the current node. If
referenceNode
is null, thennewNode
is inserted at the end of the list of child nodes.
And since myNodes[i+1]
is outside of the array bounds, it returns undefined
, which is treated as null
in this case. This means you get your desired behavior.
Edit: Link to the W3 specification of insertBefore()
这篇关于使用javascript的.insertBefore插入项作为最后一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!