D020 Create a List
Starting with the following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DOM Tasks</title>
</head>
<body>
<button id="knap">Click me</button>
<ul id="lst"></ul>
<script src="app.js"></script>
</body>
</html>
and the following JavaScript:
(function () {
let people = [
{
name: "Mikkel",
age: 17,
},
{
name: "Mathias",
age: 14,
},
];
// code
})();
Your task is to write code such that a click on the button generates a list (a collection of li’s) placed in the lst element with the text:
- Mikkel (17 years)
- Mathias (14 years)
You might:
- Use
document.createElementto create anliand itsinnerHTMLto add text. - Use the
ulelement’sappendChildto add each individualli.
Solution
(function() {
let people = [
{
name: "Mikkel",
age: 17,
},
{
name: "Mathias",
age: 14,
},
];
// Button click handler
document.getElementById('knap').onclick = function() {
let list = document.getElementById('lst');
// Clear list items if any
list.innerHTML = '';
// Add each person to the list
for (let person of people) {
let li = document.createElement('li');
li.innerHTML = `${person.name} (${person.age} years)`;
list.appendChild(li);
}
};
})();
Here is the same solution using jQuery:
```javascript $(document).ready(function () { let people = [ { name: “Mikkel”, age: 17, }, { name: “Mathias”, age: 14, }, ];
// Click event for the button $(“#knap”).click(function () { let $list = $(“#lst”); $list.empty(); // Clear existing list items
// Append each person as a list item
people.forEach(function (person) {
$list.append(`<li>${person.name} (${person.age} years)</li>`);
});
});
}); ```
Run the provided HTML, and when you click the “Click me” button, the list will be populated with the names and ages.