利用js创建元素

42 篇文章 1 订阅

第一种方式用document.write
    缺点: 创建好的元素会把之前页面中所有内容都替换了
 

document.getElementById('box').onclick=function () {
        document.write("<h1>这是动态创建H1标签</h1>")
    }

第二种方式:innerHTML="<p>内容</p>"

    document.getElementById("button").onclick=function () {
        document.getElementById("div").innerHTML="<p>这是动态创建p标签</p>";
        document.getElementById("div").style.backgroundColor="pink"
    }

第三种方式创建元素
    1.var pObj=document.createElement("标签名")-----创建元素
    2.父级元素.appendChild()

    document.getElementById("button").onclick=function () {
        //获取div
        var dvObj=document.getElementById("div");
        dvObj.style.backgroundColor="pink";
        // 创建元素
        var pObj=document.createElement("p");
        dvObj.appendChild(pObj);
        pObj.innerHTML="嘻嘻嘻";
        pObj.style.fontSize="20px"
    }

例如创建表格

<script language="javascript"> 
var o = document.body; 
//创建表格 
function createTable(w,h,r,c) 
{ 
var table = document.createElement("table"); 
var tbody = document.createElement("tbody"); 
table.width = w; 
table.height = h; 
table.border = 1;    
for(var i=1;i<=r;i++) 
{ 
var tr = document.createElement("tr"); 
for(var j=1;j<=c;j++) 
{ 
var td = document.createElement("td"); 
td.innerHTML = i + "" + j; 
//td.appendChild(document.createTextNode(i + "" + j)); 
td.style.color = "#FF0000"; 
tr.appendChild(td); 
} 
tbody.appendChild(tr);    
} 
table.appendChild(tbody); 
o.appendChild(table); 
} 
createTable(270,270,9,9); 
</script>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值