0

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>

1
  • Include the code in the question, please. All relevant details(including attempts), need to be in the question itself. Commented Aug 6, 2018 at 2:31

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.