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.οnlοad=div;

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

 

转载于:https://www.cnblogs.com/hao5599/p/4467571.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值