Getting a group of elements in JavaScript

In the previous lessons, we used the querySelector method to get one element on page. Now it's time to learn how to get a group of elements and do some operations with many elements at once.

To do this, there is a querySelectorAll method that receives all tags that match the CSS selector as an array of elements. To do something with the found elements, you need to work with the resulting array, for example, loop through it and perform some operation with each element in the loop separately.

Let, for example, we have paragraphs with the class www:

<p class="www">text1</p> <p class="www">text2</p> <p class="www">text3</p>

Let's get an array of these paragraphs, loop through them and in the loop print the texts of the found paragraphs to the console:

let elems = document.querySelectorAll('.www'); for (let elem of elems) { console.log(elem.textContent); }

And now let's add an exclamation mark to the end of each paragraph text:

let elems = document.querySelectorAll('.www'); for (let elem of elems) { elem.textContent = elem.textContent + '!'; }

Given paragraphs and a button. On button click, find all paragraphs, loop through and set the text of each paragraph to 'text'.

Given paragraphs with text and a button. By clicking on the button, write down its ordinal number at the end of the text of each paragraph.

Given inputs with numbers, a paragraph and a button. By pressing the button, find the sum of numbers from the inputs and write this sum in the text of the paragraph.

enru