创建添加

<body>
    <input type="text" id="txt1">
    <input type="button" id="btn1" value="创建">
    <ul id="ul1">
    </ul>
    <script>
        window.onload = function () {
            var oUl = document.getElementById('ul1');
            var oBtn = document.getElementById('btn1')
            // id
            var oTxt = document.getElementById('txt1')
            // dom节点
            var aLi = oUl.getElementsByTagName('li')
            // class
            // that.input = document.getElementsByClassName("js-input")[0];
            // 自动选择第一个出现的css元素
            // that.input = document.querySelector('.js-input');
            oBtn.onclick = function () {
                var oLi = document.createElement('li') //创建元素
                oLi.innerHTML = oTxt.value
                if (aLi.length > 0) {
                    oUl.insertBefore(oLi, aLi[0]) //插入元素到指定位置
                } else {
                    oUl.appendChild(oLi) //插入元素到容器末尾
                }
                oTxt.value = ''
            }
        }
    </script>
</body>

移除

<body>
    <ul id="ul1">
        <li>hjsioug<a href="javascript:;">删除</a></li>
        <li>fssaaa<a href="javascript:;">删除</a></li>
        <li>fddvfthc<a href="javascript:;">删除</a></li>
        <li>gwsvgeex<a href="javascript:;">删除</a></li>
    </ul>
    <script>
        window.onload = function () {
            var oUl = document.getElementById('ul1');
            var aA = oUl.getElementsByTagName('a');
            for(var i = 0; i < aA.length; i++){
                aA[i].onclick = function(){
                    oUl.removeChild(this.parentNode) //removeChild a标签的父节点
                }
            }
            // 删除preTag标签本身
            preTag.remove();
        }
    </script>
</body>
posted on 2023-03-25 17:08  垂序葎草  阅读(25)  评论(0编辑  收藏  举报