简体   繁体   English

通过JavaScript创建HTML元素不起作用

[英]Creating HTML element via javascript not working

I'm currently a newbie to javascript just started learning on how to create new DOM element using the javascript function document.createElement(). 我目前是javascript的新手,刚刚开始学习如何使用javascript函数document.createElement()创建新的DOM元素。 The problem is that I'm getting really confused by all these function.The code be low is what I'm trying to create 问题是我对所有这些功能感到非常困惑。代码不足是我想要创建的

I'm getting confused on how to append these element to the element having the id "date". 我对如何将这些元素附加到具有ID“日期”的元素上感到困惑。 Here is what i've done so far 这是我到目前为止所做的

 function createElements(){ //creating <div class="divider"></div> var div = document.createElement('div'); var attributeDivider= document.createAttribute('class'); attributeDivider.value="divider"; div.setAttributeNode(attributeDivider); //creating <div class="section"></div> var div2 = document.createElement('div'); var attributeSection = document.createAttribute('class'); attributeSection.value ="section"; div2.setAttributeNode(attributeSection); //creating h5 var h5 = document.createElement('h5'); var attributeH5 = document.createAttribute('id'); attributeH5.value ="test"; // creating stuff var stuff = document.createElement('Stuff'); // creating date var date = document.getElementById("date"); date.appendChild(h5); } 
 <!--This_is_where_I_need_to_append the created elements--> <p id="date">Date Created</p> <!--The elements that I need to create--> <div class="divider"></div> <div class="section"> <h5>Section 1</h5> <p>Stuff</p> </div> 

Could someone help me ? 有人可以帮我吗?

You were creating the elements, however, you were not adding them to the HTML. 您正在创建元素,但是没有将它们添加到HTML。

Try following 尝试跟随

 function createElements() { //creating <div class="divider"></div> var div = document.createElement('div'); var attributeDivider = document.createAttribute('class'); attributeDivider.value = "divider"; div.setAttributeNode(attributeDivider); //creating <div class="section"></div> var div2 = document.createElement('div'); var attributeSection = document.createAttribute('class'); attributeSection.value = "section"; div2.setAttributeNode(attributeSection); // Appending section div to divider div div.appendChild(div2); //creating h5 var h5 = document.createElement('h5'); // Adding content h5.textContent = "Section 1"; // Appending h5 to section div div2.appendChild(h5); // creating stuff var stuff = document.createElement('Stuff'); // Adding content stuff.textContent = "Stuff"; // Appending stuff element to section div div2.appendChild(stuff); // Getting date element var date = document.getElementById("date"); // Appending the structure created above date.appendChild(div); } createElements(); 
 <p id="date">Date Created</p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM