This question tests Web API (DOM) and JavaScript understanding.
You can provide the example answer below as a starting point or ask the candidate to start from scratch.
Three possible solutions are:
- Closures
- Event delegation
- Block scope (ES6 requires additional tooling. Why?)
You can achieve block scope in ES5 using IIFE however I don't think it's a good option compared to others.
What are the pros/cons of each solution? Which do you think is the best?
Can you think of other solutions?
Using JavaScript create an unordered list with 5 items.
When an item is clicked get the number of the item in the list and display it.
This answer does not work. Why? Can you fix it?
var list = document.createElement('UL');
for (var i = 1; i <= 5; i++) {
var item = document.createElement('LI');
item.appendChild(document.createTextNode('Item ' + i));
var j = i;
item.onclick = function (ev) {
console.log('Item ' + j + ' is clicked.');
};
list.appendChild(item);
}
document.querySelector('body').appendChild(list);