採用Js DOM建立結點

來源:互聯網
上載者:User

可以將HTML文檔結構理解為一棵樹。

比如下面這段,可以理解為p是div的子結點,content又是p的子結點。如果要建立新的元素,需要使用document.createElement(EleName),如果要建立新的常值內容,需要使用document.createTextNode(textName)。採用fatherNodeName.appendChild(childNodeName)可以把子結點接到父結點上面。

<div><p>content</p></div>

以下是HTML主體部分

<body><div id="testdiv"></div><div id="eggache"></div></body>

以下是js代碼

window.onload = function(){createTestdiv();createEggache();}function createTestdiv(){var para = document.createElement("p"); /*建立一個p結點*/var testdiv = document.getElementById("testdiv"); /*這是準備串連p結點的位置*/testdiv.appendChild(para);/*把p結點接上去alert(testdiv.innerHTML);*/var txt = document.createTextNode("採用creatTestNode可以建立文本結點");/*剛才建立了p結點,裡面還沒有內容*/para.appendChild(txt);/*把文本結點接在p結點上面*/}function createEggache(){var eggache = document.getElementById("eggache");var para1 = document.createElement("p");var txt1 = document.createTextNode("有的時候有些前端開發人員,");var txt2 = document.createTextNode("不好好的在html中輸入文字,");var txt3 = document.createTextNode("偏要用js dom插入文字");var emNode = document.createElement("em");emNode.appendChild(txt2);para1.appendChild(txt1);para1.appendChild(emNode);para1.appendChild(txt3);eggache.appendChild(para1);var para2 = document.createElement("p");var bold = document.createElement("b");var txt4 = document.createTextNode("我們把這種行為稱之為蛋疼。");bold.appendChild(txt4);para2.appendChild(bold);eggache.appendChild(para2);}

以下是顯示效果。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.