document.createElement()是在对象中创建一个对象,要与appendChild() 或 insertBefore()方法联合使用。
appendChild() 方法在节点的子节点列表末添加新的子节点。
insertBefore() 方法在节点的子节点列表任意位置插入新的节点
------------------------------------------------------------------------------------
insertBefore() 使用举例
var mubiao = document.getElementById("b");
mubiao.parentNode.insertBefore(a,mubiao);
自定义的insertAfter()
function insertAfter(newEl, targetEl)
{
var parentEl = targetEl.parentNode;
if(parentEl.lastChild == targetEl){
parentEl.appendChild(newEl);
}else{
parentEl.insertBefore(newEl,targetEl.nextSibling);
}
}
常用模块:
//创建form var _form=document.createElement(‘form’); _form.setAttribute(‘name’,'myform’); _form.setAttribute(‘action’,”); _form.setAttribute(‘method’,'post’); //创建表 var _table=document.createElement(‘table’); _table.setAttribute(‘border’, ’1′); _table.setAttribute(‘borderColor’, ‘red’); _table.setAttribute(‘width’, ’300′); _table.setAttribute(‘height’, ’100′); //创建一行 var _tr=_table.insertRow(_table.rows.length); // _tr.rowIndex //当前行的行号 //创建一列 var _td=_tr.insertCell(_tr.cells.length); //给<td>添加文本 _txt=document.createTextNode(‘Intitul’); _td.appendChild(_txt); alert(_td.contentEditable=true); //创建一个checkbox var _input=document.createElement(‘input’); _input.setAttribute(‘type’, ‘checkbox’); _input.setAttribute(‘name’, ‘mycheck’); _input.setAttribute(‘value’, ‘ddddd’); _td.appendChild(_input); _input.defaultChecked=true; //创建一个radio var _input=document.createElement(‘input’); _input.setAttribute(‘type’, ‘radio’); _input.setAttribute(‘name’, ‘myradio’); _input.setAttribute(‘value’, ‘ddddd’); _input.defaultChecked=true; _td.appendChild(_input); //给checkbox添加 var _label=document.createElement(‘label’); _label.setAttribute(‘for’, _input); _label.appendChild(document.createTextNode(‘my check label’)); _td.appendChild(_label) //创建一个button _input=document.createElement(‘button’); _input.setAttribute(‘type’, ‘submit’); _input.setAttribute(‘name’, ‘mysubmit’); _input.setAttribute(‘value’, ‘my submit’); _input.setAttribute(‘size’, ’130′); _td.appendChild(_input); //把表格附加到父容器内 _form.appendChild(_table); document.body.appendChild(_form); </script>