JavaScript:DOM修改

修改 HTML DOM 意味着许多不同的方面:

  改变 HTML 内容

  改变 CSS 样式

  改变 HTML 属性

  创建新的 HTML 元素

  删除已有的 HTML 元素

  改变事件(处理程序)

1. 改变一个<h2>元素的 HTML 内容 :

<body>
    <button onclick="test()">点我试试</button>

    <script>
        function test(){
            document.getElementById("hello").innerHTML = "走哇,喝点去~!";
        }
    </script>

    <h2 id="hello">你好!</h2>
</body>

2. 改变一个<h2>的 HTML 样式

<body>
    <button onclick="chou()">你瞅啥</button>

    <script>
        function chou(){
        document.getElementById("hello").style.color = "red";
        document.getElementById("hello").style.fontFamily = "华文彩云";
        }
    </script>

    <h2 id="hello">你好!</h2>
</body>

1 添加节点

<body>
    <button onclick="add()">添加</button>
    <div></div>

    <script>
    function add(){
        var img = document.createElement("img"); // <img>
        img.setAttribute("src","../lagou-html/img/cat.gif"); // <img
src="../lagou-html/img/cat.gif">
        img.setAttribute("title","小猫咪"); // <img src="../lagouhtml/img/cat.gif" title="小猫咪">
        img.setAttribute("id","cat"); // <img src="../lagouhtml/img/cat.gif" title="小猫咪" id="cat">

        var divs = document.getElementsByTagName("div");
        divs[0].appendChild(img);
}
    </script>
</body>

2 删除节点

点击按钮,把上面刚创建的图片从页面上删除

<body>
    <button onclick="add()">添加</button>
    <button onclick="del()">删除</button>
    <div>
    </div>

    <script>
        function add(){
            。。。略。。。
        }

        function del(){
            var img = document.getElementById("cat");
            img.parentNode.removeChild(img); // 必须通过父节点,才能删除子节点
        }
    </script>
</body>

3 替换节点

点击按钮,把上面刚创建的图片替换成另一张

<body>
    <button onclick="add()">添加</button>
    <button onclick="del()">删除</button>
    <button onclick="rep()">替换</button>
    <div>
    </div>

    <script>
        function add(){
        。。。略。。。
        }

        function del(){
        。。。略。。。
    }

        function rep(){
            var imgold = document.getElementById("cat");
            // 通过修改元素的属性,做的替换
            // img.setAttribute("src","../lagou-html/img/2.jpg");

            var imgnew = document.createElement("img");
            imgnew.setAttribute("src","../lagou-html/img/1.jpg");
            imgold.parentNode.replaceChild( imgnew, imgold );
        }
    </script>
</body>
原文地址:https://www.cnblogs.com/JasperZhao/p/15134944.html