0

We were given code in computer science which we were supposed to look at and explain and then we're supposed to add to it.

This is the code:

<!DOCTYPE html>
<html>
<head>
<title>Example Website</title>
</head>
<body>
<p id="demo"></p>

<script>

var array = ["example1","example2","example3"];

document.getElementById("demo").innerHTML = array[0]

</script>

</body>
</html>

What he wanted us to do now was make it print the array in separate lines with bullet points instead of just printing the first thing within the array which is 'example1'.

He said to use any resources you can from the internet to find out how and to try and remember the information found and then explain it during class.

2 Answers 2

9

Well, you can use .join(), <ul> and <li>s. The .join() helps in converting the array into a string joined by the parameter given in the .join().

<p id="demo"></p>
<script>
  var array = ["example1","example2","example3"];
  document.getElementById("demo").innerHTML = '<ul><li>' + array.join("</li><li>"); + '</li></ul>';
</script>

The above displays like:

Preview

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

3 Comments

If I used this code and added more things to my array, would I have to add to the 4th line of code so that it also arranges that part of the code into a bullet point or would I not need to change that?
@BlizzardGizzard It automatically does it based on the number of items in the array. You don't need to do anything.
@BlizzardGizzard += is appending the contents. a += b is same as a = a + b.
3

A bullet point list in HTML looks like this:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

So to print something like that you'll want to follow these steps:

  1. Print out the opening <ul> tag
  2. Loop through the array and print each array element surrounded by <li> tags
  3. Print out the closing </ul> tag

var array = ['example1', 'example2', 'example3'];

var s = '<ul>';

for (var i = 0; i < array.length; i++) {
  s += '<li>' + array[i] + '</li>';
}

s += '</ul>'

document.getElementById("demo").innerHTML = s;
<div id="demo"></div>

4 Comments

The question was asked to make the JavaScript code. :)
@PraveenKumar I know! I updated my example to include the JS on how to do it. I wanted to make sure to explain the high-level overview as well.
Could you possibly explain the '+=' expression you used? When googling this I don't see any result.
@BlizzardGizzard += is appending the contents. a += b is same as a = a + b.

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.