1

I have a predefined array list that I need to be formatted into a numbered list in HTML. I'm very new to html with javascript and am having a hard time with dom manipulation

here is my js code var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];

here is my html

<div id="fruits">



        </div>

            <h3>Fruits</h3>

`

its very bare bones and that's simply because I have no idea where to start.

2 Answers 2

2

use Array.map to generate an array of html elements and display it :

var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];

var elems = fruits.map(element => `<li>${element}</li>`);

document.querySelector('#fruitsList').innerHTML = elems.join('');
ul {
  list-style-type: decimal;
}
<ul id="fruitsList"></ul>

to display the numbers either use <ol> or <ul> with list-style-type: decimal;

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

Comments

1

You can use DOM like below. This code loops through your array, and adds each element to an ordered list.

var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];
var listOfFruits = [];
var list = document.getElementById("list");


fruits.forEach(function(element) {
  listOfFruits.push("<li>" + element + "</li>");
});

list.innerHTML = listOfFruits.join('');
<ol id="list"></ol>

Or you can use jQuery like below. This code loops through your array and appends a <li> to your html.

var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];
var listOfFruits = [];


fruits.forEach(function(element) {
  listOfFruits.push("<li>" + element + "</li>");
});

$("#list").html(listOfFruits.join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol id="list"></ol>

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.