DOM基础2

插入元素

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        window.onload=function(){
            var oBtn=document.getElementById('btn1');
            var oU1=document.getElementById('ul1');
            var oTxt=document.getElementById('txt1');

            oBtn.onclick=function(){
                var oLi=document.createElement('li');
                var aLi=oU1.getElementsByTagName('li');



                oLi.innerHTML=oTxt.value;
                //父级.appendChild(子节点) ,子节点添加到了父级末尾
                
                if(aLi.length>0)
                {
                    oU1.insertBefore(oLi,aLi[0])
                }
                else{
                    oU1.appendChild(oLi);
                }

            }
        }
    </script>
</head>
<body>
<input id="txt1" type="text"/>
<input id="btn1" type="button" value="创建li"/>
<ul id="ul1">

</ul>
</body>
</html>

删除元素

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        window.onload=function(){
            var aA=document.getElementsByTagName('a');
            var oU1=document.getElementById('ul1');

            for(var i=0;i<aA.length;i++){
                aA[i].onclick=function(){
                    oU1.removeChild(this.parentNode);

                }
            }
        }
    </script>
</head>
<body>
<ul id="ul1">
    <li>dssd <a href="javascript:;">删除</a> </li>
    <li>436d <a href="javascript:;">删除</a> </li>
    <li>d反对分割的ssd <a href="javascript:;">删除</a> </li>
    <li>ds导师sd <a href="javascript:;">删除</a> </li>
</ul>
</body>
</html>

 

posted @ 2016-11-10 15:37  缘琪梦  阅读(145)  评论(0编辑  收藏  举报