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

时间:2018-06-13 08:36:12

标签: javascript function dom

我目前是javascript的新手,刚开始学习如何使用javascript函数document.createElement()创建新的DOM元素。问题是我对所有这些功能感到困惑。代码很低是我正在努力创建的

我对如何将这些元素附加到id为“date”的元素感到困惑。这是我到目前为止所做的事情

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>

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您正在创建元素,但是,您没有将它们添加到HTML中。

尝试以下

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>