DOM Manipulation II

Learning Goals

  • Learn how to utilize document.querySelectorAll() and utilize our knowledge of iteration


document.querySelectorAll() returns a collection of all the elements that match the query.

This collection is an array-like structure of nodes (or elements) that meet the query we passed through to the document.querySelectorAll() method!

However, in order to do anything to the elements within this collection, we need to iterate through each element to perform the same action, one element at a time. The easiest way to accomplish this is our good pal for loop!


We are intentionally using the for loop throughout this lesson. If at a later point, you want to use an array prototype method on the return value of your document.querySelectorAll() method, you will need to do some additional work in order to get the expected behavior.

Let’s say we have a page with the following markup:

See the Pen Simple HTML Page by Turing School (@turing-school) on CodePen.

Let’s try out some queries:

  • document.querySelectorAll('p') will return a collection containing all of the paragraphs.
  • document.querySelectorAll('.awesome') will return a collection containing the two paragraphs with the class awesome.

Updating our HTML

Now, let’s say we want to update the text of all of the awesome paragraphs. If we try the following, it won’t work:

var awesomeParas = document.querySelectorAll('.awesome');
awesomeParas.innerText = 'This is so awesome!';

That’s because document.querySelectorAll() returns an array! We need to iterate over the array and change elements one at a time using a for loop! So to get this working, we would need to do the following:

var awesomeParas = document.querySelectorAll('.awesome');

for (var i = 0; i < awesomeParas.length; i++) {
  awesomeParas[i].innerText = 'This is so awesome!'

See the Pen Simple HTML Page (Now with JavaScript!) by Turing School (@turing-school) on CodePen.

Your Turn

Grab all of the paragraphs and change their innerText to a message of your choice.

Finished? Refactor so this happens within a function and then invoking the function.

Pair Practice

The following pair practice will require you to use your knowledge of creating functions, assigning event listeners, and utilizing what we learned about document.querySelectorAll() to achieve the functionality outlined below!

Visit this page and fork the CodePen.

See the Pen HTML Report Card by Turing School (@turing-school) on CodePen.

Pair Practice

In the CodePen above that you forked:

  • Add a button called Change Name. Find all of the elements with a class of student and change them to your name when the button is clicked!
  • Add a button called Change Grades. Find all of the elements with the class of grade. Iterate through all of them and change their content to A+s when the button is clicked.

Lesson Search Results

Showing top 10 results