# Passing a callback to work with the DOM in JavaScript

Suppose we have some group of DOM elements:

`<p class="elem">1</p> <p class="elem">2</p> <p class="elem">3</p> <p class="elem">4</p> <p class="elem">5</p>`

Let's make the function `forEach`, which will take the elements group selector as the first parameter, and the second parameter - a callback function , which will be applied to each of the found elements in turn:

`forEach('.elem', function() { // the function will be applied to each element });`

Let the elements that fall under the selector, in turn, fall into the first parameter of the callback:

`forEach('.elem', function(elem) { console.log(elem); // outputs the found elements one by one });`

Let's use our function to find all elements with the class `elem` and apply a callback for each element found, which will square the text of each element:

`forEach('.elem', function(elem) { elem.textContent = elem.textContent ** 2; });`

Let's now write the implementation of the `forEach` function:

`function forEach(selector, func) { let elems = document.querySelectorAll(selector); for (let elem of elems) { func(elem); } }`

Given paragraphs. Add an exclamation mark to the end of each paragraph text using the forEach function we created.

← →
↑
en ru