"Arrays" in the DOM

Completed Code

HTML

<!DOCTYPE html>
<html>
<body>
    <h1>DOM CHALLENGE!</h1>
    <p>I believe in you!</p>
    <h4>You can do it!</h4>
    <p>Just Think</p>
    <h1>Well, what's your answer?</h1>
    <button onClick="myFunction()">Click me!</button>
<script src="arrDom.js"></script>
</body>
</html>

JavaScript

function myFunction() {
    var myNodelist = document.querySelectorAll("p");
    var i;
    for (i = 0; i < myNodelist.length; i++) {
        myNodelist[i].style.color = "blue";
        myNodelist[i].style.fontStyle ="italic";
    }
}

NodeList

The main component of this challenge is a NodeList. A NodeList is very similar to an HTMLCollection in that both return array-like objects. NodeLists differ in that they can only be accessed by their index number and can contain attribute nodes and text nodes. That's why we are able to change the color and style of our <p> tags. Please note, a NodeList is NOT an Array. It looks like an array, and can be referenced like an array, but you CANNOT use array methods on a NodeList.

Explanation

  • document.querySelectorAll("p") - all <p> tags in the HTML are selected.

  • For Loop - The text is changed to blue and put in italics for each <p> tag.

open-in-browser

If you don't have it already, install the open-in-browser extension by coderfree to run HTML from VS Code. Once you have it installed, make sure you are on your .html page and then type ctrl+alt+o on Windows or cmd+alt+o on Mac to select a browser to run the HTML in. Ctrl+K and then D (hold ctrl and k, release and press d) runs the HTML in your default browser. I would assume Mac users need to just use cmd instead of ctrl.

Output

Here's the proper output after clicking the button.

Last updated