Passing an index number to a callback in JavaScript
Let's make it so that if the second parameter is written in our callback function, let it contain the index number of the element in the found set of elements:
forEach('.elem', function(elem, index) {
console.log(elem); // outputs the element
console.log(index); // displays the element's index
});
With this parameter, we can, for example, add to the end of each element its index:
forEach('.elem', function(elem, index) {
elem.textContent = elem.textContent + index;
});
Let's refactor our forEach function code to implement the described:
function forEach(selector, func) {
let elems = document.querySelectorAll(selector);
for (let i = 0; i < elems.length; i++) {
func(elems[i], i);
}
}
Given paragraphs. Using the function forEach
we created for each paragraph, add its index to
the beginning of it.