简体   繁体   中英

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(). 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". 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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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