0

Hello experts i am trying to loop through an Array and showing it as an HTML in the body. I am using template literals for this. But when i use the <li> tag inside template literals, it is not works. Can you check and let me know which is the correct method. Thanks in advance!. The code is as follows:

    let uls = "<ul>";
    for(i=0;i<a.length;i++){
     `${uls+=a[i]}`;
    }
    let ulc = "</ul>";
    let list = uls+=ulc;
    document.write(list);
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
Ren Jitsm
  • 429
  • 1
  • 4
  • 16

5 Answers5

2

You can create elements in JavaScript using document.createElement. Then just append the element in your HTML using appendChild.

Here's a little demo

let body = document.querySelector("body");
let ul = document.createElement("ul");

for(let i=0; i<5; i++){
    ul.innerHTML += `<li>${i+1}</li>`;
}

body.appendChild(ul)
ahsan
  • 1,409
  • 8
  • 11
1

This is wrong:

`${uls+=a[i]}`

It should be:

uls += a[i]

There is no need to use a template literal when your expression does not include a string literal. You are simply appending the contents one one variable to another.

kmoser
  • 8,780
  • 3
  • 24
  • 40
1

There are several possibilities. Here are a few ideas.

By the way: don't use document.write.

const lis = [`li 1`, `li 2`, `li 3`];

document.body.insertAdjacentHTML(
  "beforeend",
  `<ul>${lis.map(li => `<li>${li}</li>`).join("")}</ul>`
);

// Or use DOM manipulation
const ul = document.createElement("ul");
lis.forEach(content => {
    const li = document.createElement("li");
    li.appendChild(document.createTextNode(content));
    ul.appendChild(li);
  });
document.body.appendChild(ul);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

Using forEach loop instead of for loop it is much easier to add list items , as using normal for loop u need to add index alongside ...

See this example :

  // Defining a variable and adding opening tag for list 
  let list = "<ul>";
  
  // Looping for each value in list array
  let list_array = ["a","b" ,"c"]
  list_array.forEach( li =>{
    list += `<li> ${li} </li>`
  })
  
  // Adding closing tag
  list += "</ul>";
  document.write(list)
  console.log(list)

Using normal for Loop

  let a = ["a" , "b" , "c"]
  let ul = "<ul>";
  for (i = 0; i < a.length; i++) {
      ul += `<li>${a[i]}</li>`
  }
   ul += "</ul>";

  document.write(ul);
Sanmeet
  • 1,191
  • 1
  • 7
  • 15
1

You can create elements in JavaScript using document.createElement. Then just append the element in your HTML using appendChild.

Here's a little demo

let body = document.querySelector("body"); let ul = document.createElement("ul");

for(let i=0; i<5; i++){ ul.innerHTML += <li>${i+1}</li>; }

body.appendChild(ul)