LearnFrenzy
Sign in Take a free test

DOM Manipulation · DOM Coding Problems · Question 1

Render an array as a list in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The page contains this HTML:

<ul id="leaders"></ul>

Render the leaderboard array as list items (rank, name and score) inside #leaders using a DocumentFragment, marking the top scorer with the class "gold", and print the resulting HTML.

Solution
main.js
const leaders = [
  { name: "Asha", score: 980 },
  { name: "Ravi", score: 1020 },
  { name: "Meera", score: 875 },
];
const list = document.getElementById("leaders");
const fragment = document.createDocumentFragment();

[...leaders].sort((a, b) => b.score - a.score).forEach((p, i) => {
  const li = document.createElement("li");
  li.textContent = `${i + 1}. ${p.name} – ${p.score}`;
  if (i === 0) li.classList.add("gold");
  fragment.append(li);
});
list.append(fragment);

console.log(list.outerHTML.replaceAll("<li", "\n  <li").replace("</ul>", "\n</ul>"));

Output Verified by running it on Node.js

<ul id="leaders">
  <li class="gold">1. Ravi – 1020</li>
  <li>2. Asha – 980</li>
  <li>3. Meera – 875</li>
</ul>

Sorting a copy keeps the original data unchanged; the fragment lets all three items enter the page in one insertion; textContent keeps names safe.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links