如何在之前追加孩子。原型 [英] How to append child before. prototype

查看:102
本文介绍了如何在之前追加孩子。原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JavaScript库制作网站。如果用户在下拉(选择)框中选择一个选项,则必须添加标签和文本框。这是我用appendChild选项做的。 appenChild选项唯一的问题是这些项目总是被添加到used元素中的项目之后。这是我的代码:

  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);

这里容器是必须添加项目的元素。唯一的问题是项目添加在元素的末尾,我想在html元素的开头添加项目。

解决方案

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

  container.insertBefore(newFreeformLabel,container.firstChild); 


I making a website with the javascript library. If the user select a option on a dropdown (select) box there must be added a label and a textbox. This I do with the appendChild option. The only problem with the appenChild option is that the items always be added after the items in used element. This is my code:

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);

Here container is the element where the items must be added. The only problem is that the items are added on the end of the element and I want to added the items on the beginning of the html element.

解决方案

As well as appendChild, DOM nodes have an insertBefore method

container.insertBefore(newFreeformLabel, container.firstChild);

这篇关于如何在之前追加孩子。原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆