JavaScript--元素对象方法setAttribute() 和appendChild()

appendChild() 方法可向节点的子节点列表的末尾添加新的子节点

setAttribute() 方法创建或改变某个新属性。如果指定属性已经存在,则只设置该值

<!DOCTYPE html>
<html>

    <head id="head">
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            window.onload = function() {
                //根据id获得对象
                var head = document.getElementById("head");
                //创建元素对象
                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", "js/jquery-3.1.1.min.js");
                //添加对象到相应的节点
                head.appendChild(script);
            }
            
            function test(){
                //根据id获得对象
                var firstdiv=$("#firstdiv");
                //创建元素对象
                var h1=document.createElement("h1");
                //创建文本对象
                var content=document.createTextNode("Hello World!");
                //添加对象到相应的节点
                h1.appendChild(content);
                firstdiv.append(h1);
            }
        </script>
    </head>

    <body>
        <div id="firstdiv"></div>
        <button onclick="test();">测试jQuery</button>
    </body>

</html>
原文地址:https://www.cnblogs.com/fengfuwanliu/p/10173139.html