用.appendChild()方法能否将元素插入到另一个元素的开头?

98
如果用户在下拉框中选择了一个选项,则必须添加一个标签和一个文本框。使用 appendChild,这些元素将被添加到 container 的末尾。
var newFreeformLabel = document.createElement('label');
newFreeformLabel.innerHTML = 'Omschrijving:';

var newFreeformField = document.createElement('input');
newFreeformField.className = 'textfield';
newFreeformField.name = 'factuur_orderregel[]';

var newFreeformSpacer = document.createElement('div');
newFreeformSpacer.className = 'spacer';

container.appendChild(newFreeformLabel);
container.appendChild(newFreeformField);
container.appendChild(newFreeformSpacer);
问题在于这些元素应该插入到container的开头,而不是结尾。
在 PrototypeJS 中有解决方案吗?
6个回答

185

除了 appendChild,DOM 节点还有一个 insertBefore 方法。

container.insertBefore(newFreeformLabel, container.firstChild);

13
请注意,即使容器最初没有任何元素,此方法也适用。 - starbeamrainbowlabs

116

现代解决方案

要将子元素添加到父元素的开头,请使用prepend

parent.prepend(newChild)

要在父元素末尾添加内容,请使用append

parent.append(newChild)

另外,如果您想将元素添加到另一个子元素中,可以使用以下其中之一:

child1.after(newChild)  // [child1, newChild, child2]

child1.before(newChild) // [newChild, child1, child2]

高级用法

  1. 您可以传递多个值(或使用展开运算符...)。
  2. 任何字符串值都将作为文本元素添加。

示例:

parent.prepend(newChild, "foo")  // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")  // [child1, child2, "bar", newChild, "fizz"]

相关的DOM方法 - child.replaceWith

文档

Can I Use


这个答案有效,第一个答案对我没用。 - Richard Aguirre

11

4
这个问题被标记为prototypejs,所以这确实应该是正确的答案。 - thomas-peter

1
container.
    insert({
        // key is position
        // 'before', 'after', 'top' and 'bottom' are allowed
        top: new Element('label').
            update('Omschrijving:')
    }).
    insert({
        top: new Element('input').
            addClassName('textfield').
            writeAttribute('name', 'factuur_orderregel[]')
    }).
    insert({
        top: new Element('div').
            addClassName('spacer')
    });

我认为Prototype的Element.insert在使用before/after时有些棘手。例如,如果您想要在稍后的代码中将.spacer放置在.textfield之前,您需要执行类似以下的操作:

container.
    down('.textfield').
    insert({
        before: new Element('div').
            addClassName('spacer')
    });

如果你熟悉 DOM API 的 Element.insertBefore,这可能会让你感到有些不直观。因为你并没有将 .spacer 插入到 .textfield 中,而是插入到了 container 中,在 .textfield 之前。


0
如果我及时看到了Gareth的解决方案,我可能会选择那个,但事实上我使用了:
$('toggle_product').innerHTML = insertContent + $('toggle_product').innerHTML;

由于IE8中Prototypes的insert()函数返回错误...


使用那个解决方案,您将失去所有事件。 - danilo

0

你的答案可以通过提供更多的支持信息来改进。请编辑以添加进一步的细节,比如引用或文档,这样其他人就能确认你的答案是否正确。你可以在帮助中心找到关于如何写好答案的更多信息。 - Community
虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。-【来自审查】 - SelVazi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接