首页 > 代码库 > 创建新元素插入

创建新元素插入

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>

</style>

</head>
<body>
<input id = "txt1" type = "text" value = ‘‘ />
<input id = "btn1" type = "button" value = "创建li" />
<ul id = "ul1">
</ul>
<script type="text/javascript">
    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);
        //在父级.appendChicd(子节点);
        oLi.innerHTML = oTxt.value;
        //oUl.appendChild(oLi);
        if(aLi.length>0)
        {
            oUl.insertBefore(oLi,aLi[0]);
        }

        else
        {
            //IE下如果一开始没有li就不会有aLi[0],会报错
            oUl.appendChild(oLi);
        }
        oTxt.value = ‘‘;
    }
    //父级.appendChild(子节点);
    //父级.insertBrfore(子节点,在谁之前);
    //父级.removeChild(哪个子节点);
</script>
</body>
</html>

 

创建新元素插入