简体   繁体   中英

Javascript help on dynamically creating html elements and populating the element onto the DOM

So in the script tag here I have an array myArr that is printed into p tag in the html:

<html>
  <body>
<h1>Header 1</h1>
<div>
  <p id="test"></p>
</div>
</body>
 </html> 
<script> 
var myArr = ["abc", 123, "test"];
document.getElementById('test').innerHTML = myArr; 
</script>

All that works and is good. So, I have a couple of questions about this, as I'm pretty new to javascript.

I know how to iterate through the array and print out each element within the script tag. But how would I be able to display it into the html? Is there a way to dynamically create the p tags with the element from the array as the contents?

And would I be able to easily add stying into the dynamically created p tag?

Can this kind of thing be done using something like jquery? or another popular simple javascript library?Unfortunately, I will be unable to run a full fledged javascript framework. I am only able to run a basic library.

I attempted a try here:

 var my_arr = ["test", "abc", 123]; var arr_length = my_arr.length; for (i = 0; i < arr_length; i++) { document.createElement("p"); document.getElementById('test').innerHTML = arr_length; my_arr[i] } 
 <h2>My First Web Page</h2> <p>My first paragraph.</p> <div id="test"> </div> 

You just need to forEach over the array. Inside the callback, create a p , append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:

 const test = document.getElementById('test'); const my_arr = ["test", "abc", 123]; my_arr.forEach((item) => { test.appendChild(document.createElement('p')) .textContent = item; }); 
 <h2>My First Web Page</h2> <p>My first paragraph.</p> <div id="test"> </div> 

Array methods are generally preferrable to for loops, but if you really wanted to use a for loop like in your original code, you would have to set the textContent of the created p to my_arr[i] , in addition to appending the p to test :

 var my_arr = ["test", "abc", 123]; var arr_length = my_arr.length; const test = document.getElementById('test'); for (i = 0; i < arr_length; i++) { const p = document.createElement("p"); p.textContent = my_arr[i]; test.appendChild(p); } 
 <h2>My First Web Page</h2> <p>My first paragraph.</p> <div id="test"> </div> 

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