【JS--DOM-节点操作2】--createElement()、appendChild()、insertBefore()、自定义的insertAfter()

来源:互联网 发布:单片机几个p口的区别 编辑:程序博客网 时间:2024/06/07 19:01

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

常用模块:

//创建formvar _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);//创建一个checkboxvar _input=document.createElement(‘input’);_input.setAttribute(‘type’, ‘checkbox’);_input.setAttribute(‘name’, ‘mycheck’);_input.setAttribute(‘value’, ‘ddddd’);_td.appendChild(_input);_input.defaultChecked=true;//创建一个radiovar _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>