Создание элемента HTML через JavaScript не работает - PullRequest
0 голосов
/ 13 июня 2018

В настоящее время я новичок в javascript, только что начал изучать, как создать новый элемент DOM, используя функцию javascript document.createElement ().Проблема в том, что я действительно запутался во всех этих функциях. То, что я пытаюсь создать, - это низкий код -

Я запутался в том, как добавить эти элементы к элементу, имеющему идентификатор"Дата".Вот что я сделал до сих пор

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 голосов
/ 13 июня 2018

Вы создавали элементы, но не добавляли их в 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...