Home > OS >  How to put pre-existing text in an ordered list?
How to put pre-existing text in an ordered list?

Time:08-16

I have some pre-existing recipe ingredients that I want to put into an order list in the HTML file. Like the list below, is there a way to put each ingredient into the list without manually copy and pasting it one by one? I am currently trying to use emmet abbreviations and so far I tried ol>li*13> ["paste in the ingredients"] it does not work.

e.g.

Sticky Garlic Shrimp

salt
pepper
sesame seeds
lemon slices
cooked brown rice (to serve)
1 tablespoon reduced-sodium soy sauce
1 teaspoon fresh ginger, minced
1 tablespoon olive oil
1 spring onion
1/4 teaspoon crushed chili flakes (optional)
3 cloves of garlic, minced
3 tablespoons honey
1400g uncooked shrimp, peeled & deveined

and I want it in the following:

  1. salt
  2. pepper
  3. sesame seeds
  4. etc

CodePudding user response:

Yes, you can do it by looping through your array in JavaScript, and appending them one by one:

Create an HTML element for your list:

<div id="food_div"></div>

JavaScript at the bottom of the HTML file:

var food_items = ["salt", "pepper""]
var str = '<ul>'

food_items.forEach(function(el) {
   str  = '<li>'  el   '</li>';
}); 

str  = '</ul>';
document.getElementById("food_div").innerHTML = str;

CodePudding user response:

As the other answer points out, doing this with JS is the way to go, but if you don't want to convert your list to an array first, let JS handle that and you can use split() to create the array for you.

// Set a varaible to your multiline list and use the backticks to create a string literal.
let ing = `salt
pepper
sesame seeds
lemon slices
cooked brown rice (to serve)
1 tablespoon reduced-sodium soy sauce
1 teaspoon fresh ginger, minced
1 tablespoon olive oil
1 spring onion
1/4 teaspoon crushed chili flakes (optional)
3 cloves of garlic, minced
3 tablespoons honey
1400g uncooked shrimp, peeled & deveined`;

// now get your array using the '\n' new line selector to create each value.
let ing_array = ing.split('\n');
// the parent div
let ing_parent = document.getElementById('ingredients');

// now loop through each element in the array.
ing_array.forEach( elem => {
  // create an li element
  let li_elem = document.createElement('li');
  // add the text from the array to the li
  li_elem.append(elem);
  // append the li element to the ul.
  ing_parent.append(li_elem);
});
<ul id="ingredients">
</ul>

  • Related