zoukankan      html  css  js  c++  java
  • DOM创建移除替换元素

    创建元素:document.createElement('要创建的标签名')

    将元素(子级)添加到另一个元素(父级)中:元素(父级) . appendChild('子级')

    将元素(子级)插入到另一个元素(另一个子级)的前面: 元素(被插入元素的父级)insertBefore(插入的新元素,被插入的元素)

    替换子节点:元素(被替换节点的父级) . replaceChild(新的子节点,被替换的子节点)

    删除子节点:元素(删除元素的父级) . removeChild (要删除的元素)

    案例说明:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
    <style type="text/css">
    div{ 500px;margin: 20px auto;}
    h4{border-bottom: 2px solid #000;line-height: 30px;}
    ul{border: 1px solid #ccc;}
    li{list-style: none;}
    .li1{height: 50px;line-height: 50px;}
    .delete{float: right;}
    p{font-style: italic;}
    textarea{ 100%;height: 100px;resize: none;padding: 0;}
    input{ 100%;height: 50px;font-size: 16px;}
    </style>
    </head>
    <body>
      <div id="box">
        <h4>留言内容:</h4>
        <ul>
          <li class="li1">请输入内容......</li>
        </ul>
        <textarea></textarea>
        <input type="button" value="发表留言">
      </div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        var Ul = box.getElementsByTagName('ul')[0];
        var li1 = Ul.getElementsByClassName('li1')[0];
        var button = box.getElementsByTagName('input')[0];
        var Tex = box.getElementsByTagName('textarea')[0];
        button.onclick = function(){
          if(Tex.value == '' || /^s*$/.test(Tex.value)){
            alert("请输入内容......");
          }else{
            var str = Tex.value;
            if(Ul.children[0].className == 'li1'){
              Ul.innerHTML = '';
            }
            //创建元素
            var Li = document.createElement('li');
            //给元素添加内容
            Li.innerHTML = str;
            //把元素添加到另一个元素中
            Ul.appendChild(Li);
            var oA = document.createElement('a');
            oA.href = 'javascript:;';
            oA.innerHTML = '删除';
            oA.className = 'delete';
            oA.onclick = function(){
              //删除元素
              this.parentNode.remove(this.parentNode);
              if(!Ul.children[0]){
                Ul.appendChild(li1);
              } 
            }
            Li.appendChild(oA);
          }
          Tex.value = '';
        }
      </script>
    </body>
    </html>
  • 相关阅读:
    冲不动刺。。
    第六次作业——团队作业
    LeetCode 638 Shopping Offers
    windows 64bit 服务器下安装32位oracle database 11g 问题集
    Codeforces Round #379 (Div. 2) D. Anton and Chess 模拟
    Codeforces Round #381 (Div. 2) D. Alyona and a tree 树上二分+前缀和思想
    HDU 1171 Big Event in HDU 多重背包二进制优化
    HDU 3401 Trade dp+单调队列优化
    HDU 5976 Detachment 打表找规律
    HDU 5973 Game of Taking Stones 威佐夫博弈+大数
  • 原文地址:https://www.cnblogs.com/rickyctbur/p/11122862.html
Copyright © 2011-2022 走看看