JavaScript(appendChild添加节点)

首先,我们有一个编辑器,有一个简单的HTML页面,页面的级别分别 --> html  -->head[title,meta,script,link] -- body,然后再新建一个index.js页面,专门编写javascript代码。后面再建一个style.css页面。

html页面

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>DOM</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="js/Demo.js"></script>
</head>
<body>
    <div class="main" id="main">
        <center>
            <div id="test"></div>
        </center>
    </div>
</body>
</html>
View Code

css页面

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio,video
{margin: 0; padding: 0; border: 0; font-size: 100%; font: "Microsoft Himalaya"; vertical-align:baseline;}
body
{font-size: 1.025rem;}
/*固定css样式--顶部代码*/
.main
{position:absolute;top:0;bottom:0;left:0;right:0;background-color:#b9b7b7;}
.main center
{position:absolute;top:2%;bottom:2%;left:1%;right:1%;background-color:#ffffff;border-radius:12px;}
.main center div#test
{position:relative;margin:1% auto;padding:6px 0px;background:rgba(242, 248, 248, 0.93);border:1px solid rgba(241, 242, 243, 0.95);box-shadow:2px 0px 2px #ffffff;}
css

javascript页面

function div(){
    var test = document.getElementById("test");
    
    var p = document.createElement("p");
    var i = document.createElement("i");
    var text = "this is javaScript";
    var here = document.createTextNode(text);
        i.appendChild(here);
        p.appendChild(i);//在p内增加一个i文本

        test.appendChild(p);//在div内增加一个p节点
}
View Code

此时,在web浏览器看到页面上显示的信息,this isjavascript英文字斜的表示用了<i>标签。

在html页面,我们只是在body内给div块新建了一个id,然后,在javascript内通过getElementById(id)获取页面的id即可,后面通过appendchild来给节点添加子节点,就这样一步一步走,不出意外,就可以实现我们想要的。

还没有完,之前我们没有说如何在页面上加载js函数,所以在javascript页面的function div(){}后面还要再加一行代码。 window.onload=div;

写到这里,也就搞定了,当然这些都是基础,如果内容有问题,希望您提出来,以免误导其他人学习,我希望大家互相成长。^_^

原文地址:https://www.cnblogs.com/hao5599/p/4467571.html