insertBefore(),appendChild()创建添加列表实例

定义:

insertBefore() 方法在您指定的已有子节点之前插入新的子节点。

语法:

父级.insertBefore(新的子节点,指定的已有子节点) 

实例:

<input id="txt1" type="text"/>
<input id="btn1" type="button" value="创建li"/>
<ul id="ul1">
</ul>
window.onload=function ()
{
    var oBtn=document.getElementById('btn1');
    var oUl=document.getElementById('ul1');
    var oTxt=document.getElementById('txt1');
    oBtn.onclick=function ()
    {
        var oLi=document.createElement('li');
        var aLi=oUl.getElementsByTagName('li');
        
        oLi.innerHTML=oTxt.value;
        
        //父级.appendChild(子节点);
        if(aLi.length>0)
        {
            oUl.insertBefore(oLi, aLi[0]);
        }
        else
        {
            oUl.appendChild(oLi);
        }
    };
};

当ul中没有li时oUl.insertBefore(oLi, aLi[0]);会报错,所以判断aLi.length为0时使用oUl.appendChild(oLi);

我们这里没有涉及到的,但程序中要注意的是appendChild()是先把元素从原有父级中删除,在添加到新的父级。

posted @ 2016-12-29 10:26  安静的女汉纸  阅读(251)  评论(0编辑  收藏  举报