JS · Lesson 1

Document Object Model (DOM)

Finding and changing parts of the page

HTML builds the page and CSS decorates it. JavaScript can change the page while it is open. To change a part, JavaScript first has to find it, and the DOM is how it finds it.

What you'll learn

  • What JavaScript is and how to write your first line of it.
  • How the browser turns your HTML into a tree called the DOM.
  • How to find elements with getElementById and querySelector, change them with innerHTML, and add new ones with appendChild.

Welcome to JavaScript

JavaScript is the third language of the web. HTML says what each part of the page is, and CSS says how it looks. JavaScript says what the page does: it can change text, add new parts and react when someone clicks.

When the browser opens your HTML, it builds a copy of the page in its memory. This copy is called the DOM, short for Document Object Model. JavaScript works on this copy. When JavaScript changes the DOM, the page on the screen changes right away. Your HTML file stays the same.

The DOM is shaped like a tree. Every tag becomes a piece of the tree, called an element, and tags written inside another tag hang under it.

Think of a family tree. Lola is at the top, her children are under her, and their children are under them. Each person who has someone under them is a parent, and the people under them are their children. To find someone, you can use their ID card number, which only one person has (getElementById), or describe them, like "the first one wearing glasses" (querySelector). You can change what's written on their name card (innerHTML), and when a baby is born, it joins the end of its parent's line of children (appendChild).

The tree follows the HTML: <head> and <body> are written inside <html>, so they hang under it. The yellow boxes are elements JavaScript finds in this lesson, and the dashed box is a new element that JavaScript adds.

A closer look

Reading a line of JavaScript

A line of JavaScript is read from left to right, and each dot means "go inside and use". Here is a line from this lesson, split into its parts:

A method is an action, and it always has parentheses ( ) after its name. What you put inside them tells the action what to work with. A property is a part of something, so it has no parentheses.

Statements, quotes and capital letters

Each line in this lesson is one statement: one instruction for the browser. The browser runs the statements from top to bottom, one at a time. A statement ends with a semicolon ;. Text goes inside quotes, like "headline". Text in quotes is called a string. JavaScript also cares about capital letters: getElementById works, but getelementbyid doesn't.

The console

console.log( ) writes a message in the console, a small panel for the coder. Visitors to the page don't see it. It's the easiest way to check what your code found. In these lessons, the console is shown under each mini browser. In a real browser, you can open it by pressing F12 and choosing Console.

getElementById or querySelector?

Both find an element. getElementById("headline") looks only at ids, so you write the id name alone, with no #. querySelector( ) uses a CSS selector, the same kind you wrote in the CSS lessons: "#headline" for an id, ".intro" for a class, "li" for a tag. If many elements match, querySelector gives you only the first one.

innerHTML: the part between the tags

innerHTML is everything between an element's start tag and its end tag. The tags themselves are not part of it.

Reading innerHTML gives you that text. Giving it a new value with = replaces the old content. If the new value has tags in it, like <strong>, they become real HTML.

When nothing is found: null

If no element matches, getElementById and querySelector give back null, which means "nothing". Trying to change the innerHTML of nothing stops your code with an error in the console. The common mistakes below show what that looks like.

Where JavaScript goes

In these lessons, each code box has three tabs: HTML, CSS and JS. The JS tab opens first. The browser runs it after the page is built, just like the JS tab of the WebCore code editor. In a single HTML file, you can put the same code between <script> and </script>, just before </body>. Putting it at the end means every element is already in the DOM when your code looks for it.

Let's build it

Let's bring the Front Page Bytes page to life. The HTML and CSS stay the same in every step: a headline, a short intro and a list of stories. Only the JavaScript changes. Each code box opens on the JS tab with the new lines highlighted, and the console under the mini browser shows what console.log writes.

Step 1: Write your first line of JavaScript

Your code
console.log("Hello from JavaScript!");
What you see

Console

    Nothing here yet. console.log() writes here.

    console.log("Hello from JavaScript!"); writes the text inside the quotes in the console. The page itself doesn't change. Seeing your message in the console tells you that your JavaScript is running.

    Step 2: Find an element by its id and read it

    Your code
    console.log("Hello from JavaScript!");console.log(document.getElementById("headline").innerHTML);
    What you see

    Console

      Nothing here yet. console.log() writes here.

      document.getElementById("headline") finds the element with id="headline": the <h1>. .innerHTML then reads what's inside it.

      Putting all of that inside console.log( ) writes the answer in the console: Front Page Bytes. Open the HTML tab to find the same id.

      Step 3: Change what's inside

      Your code
      console.log("Hello from JavaScript!");console.log(document.getElementById("headline").innerHTML);document.getElementById("headline").innerHTML = "Today's Bytes";
      What you see

      Console

        Nothing here yet. console.log() writes here.

        This time innerHTML comes before an =. That gives it a new value, so the headline on the page now says Today's Bytes.

        Look at the console: it still says Front Page Bytes. Line 2 read the headline before line 3 changed it, because the browser runs the lines from top to bottom.

        Step 4: Find an element with a CSS selector

        Your code
        console.log("Hello from JavaScript!");console.log(document.getElementById("headline").innerHTML);document.getElementById("headline").innerHTML = "Today's Bytes";document.querySelector(".intro").innerHTML = "Tech news for <strong>everyone</strong>.";
        What you see

        Console

          Nothing here yet. console.log() writes here.

          document.querySelector(".intro") finds the element with class="intro", using a dot just like in CSS. The new text has <strong> tags in it. innerHTML turns them into real HTML, so everyone shows in bold.

          Step 5: querySelector picks the first match

          Your code
          console.log("Hello from JavaScript!");console.log(document.getElementById("headline").innerHTML);document.getElementById("headline").innerHTML = "Today's Bytes";document.querySelector(".intro").innerHTML = "Tech news for <strong>everyone</strong>.";document.querySelector("li").innerHTML = "New phones are here!";
          What you see

          Console

            Nothing here yet. console.log() writes here.

            There are two <li> elements, but querySelector("li") gives back only the first one. So only the first story changes. The second one stays the same.

            Step 6: Add a new story with appendChild

            Your code
            console.log("Hello from JavaScript!");console.log(document.getElementById("headline").innerHTML);document.getElementById("headline").innerHTML = "Today's Bytes";document.querySelector(".intro").innerHTML = "Tech news for <strong>everyone</strong>.";document.querySelector("li").innerHTML = "New phones are here!";const story = document.createElement("li");story.innerHTML = "Robots help farmers plant rice";document.getElementById("stories").appendChild(story);
            What you see

            Console

              Nothing here yet. console.log() writes here.

              Adding a new part to the page takes three lines:

              • document.createElement("li") makes a new, empty <li>. const story = gives it a name, so the next lines can use it. You'll learn more about names like this, called variables, in JS Lesson 2.
              • story.innerHTML = ... puts text inside the new item.
              • .appendChild(story) adds it inside the list with id="stories", after the last story.

              Until appendChild runs, the new item exists only in JavaScript's memory and isn't on the page.

              Quick notes

              console.log( ) Write in the console
              console.log("Hello!");

              How to use

              • console.log("text"); Writes the text in the console.
              • console.log(5 + 2); Works out the answer first, then writes 7.
              • The console is for you, the coder. Visitors to the page don't see it.

              Examples

              1. Check that your JavaScript runs at all.

                console.log("It works!");
              2. See what is inside an element.

                console.log(document.getElementById("headline").innerHTML);
              getElementById( ) Find one element by its id
              document.getElementById("headline");

              How to use

              • document The whole page, ready for JavaScript to use.
              • getElementById("name") The id to look for, in quotes, without a #.
              • You get back the one element with that id, or null when there is none.

              Examples

              1. Change a heading with id="headline".

                document.getElementById("headline").innerHTML = "Breaking news";
              2. Read the price shown in an element with id="price".

                console.log(document.getElementById("price").innerHTML);
              querySelector( ) Find the first match of a CSS selector
              document.querySelector(".intro");

              How to use

              • "#headline" The element with id="headline".
              • ".intro" The first element with class="intro".
              • "li" The first <li> on the page.
              • "#stories li" The first <li> inside the element with id="stories".

              Examples

              1. Change the first paragraph with class="intro".

                document.querySelector(".intro").innerHTML = "Welcome!";
              2. Change the first item of one list only.

                document.querySelector("#stories li").innerHTML = "Updated story";
              3. Find an element by its id, the CSS way.

                document.querySelector("#headline").innerHTML = "Hello";
              innerHTML Read or change what's inside
              document.getElementById("headline").innerHTML = "Hi!";

              How to use

              • element.innerHTML Reads what is inside the element now.
              • element.innerHTML = "text"; Replaces everything inside with new text.
              • "<strong>Hi</strong>" Tags inside the quotes become real HTML.

              Examples

              1. Replace a heading's text.

                document.getElementById("headline").innerHTML = "Game day!";
              2. Make one word bold.

                document.querySelector(".intro").innerHTML = "Read <strong>today</strong>.";
              3. Empty an element.

                document.getElementById("stories").innerHTML = "";
              createElement( ) Make a new element
              const story = document.createElement("li");

              How to use

              • document.createElement("li") Makes a new, empty <li>. The tag name goes in quotes, without < >.
              • const name = ...; Gives the new element a name, so later lines can use it.
              • The new element is not on the page yet. appendChild puts it there.

              Examples

              1. Make a new list item with text.

                const item = document.createElement("li");item.innerHTML = "Milk";
              2. Make a new paragraph.

                const note = document.createElement("p");note.innerHTML = "Thanks for reading!";
              appendChild( ) Add a child at the end
              document.getElementById("stories").appendChild(story);

              How to use

              • parent.appendChild(child) Adds child inside parent, after its last child.
              • parent The element that will hold the new one, like a <ul>.
              • child An element made with createElement. Plain text won't work here.

              Examples

              1. Add a new item to a shopping list.

                const item = document.createElement("li");item.innerHTML = "Eggs";document.getElementById("shopping").appendChild(item);
              2. Add a paragraph at the end of the page.

                const note = document.createElement("p");note.innerHTML = "The end.";document.querySelector("body").appendChild(note);

              Common mistakes

              These are mistakes many beginners make. Each mini browser shows what really happens, and the console shows the error message the browser gives.

              Using the wrong capital letters

              The mistake
              console.log("Changing the headline...");document.getElementByID("headline").innerHTML = "Today's Bytes";
              What you see

              Console

                Nothing here yet. console.log() writes here.

                getElementByID has a capital D. To JavaScript, that is a different name, and no method has it. The console says it is not a function, the code stops, and the headline stays the same.

                Tip: Copy method names letter for letter: getElementById ends with a capital I and a small d.

                Writing # inside getElementById

                The mistake
                console.log("Changing the headline...");document.getElementById("#headline").innerHTML = "Today's Bytes";
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  getElementById("#headline") looks for an element whose id is #headline, with the #. There isn't one, so it gives back null. Setting the innerHTML of null causes the error in the console: Cannot set properties of null.

                  Tip: Give getElementById the id name only. The # belongs to querySelector, as in querySelector("#headline").

                  Giving appendChild plain text

                  The mistake
                  console.log("Adding a story...");document.getElementById("stories").appendChild("Robots help farmers plant rice");
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    appendChild only accepts an element. A string in quotes is plain text, so the browser stops with an error saying the value is not of type 'Node'. A node is any piece of the DOM tree.

                    Tip: Make the element with createElement, put the text in it with innerHTML, then append the element.

                    Test your knowledge

                    Write JavaScript in the JS tab. Open the HTML tab to see the ids and classes you can use. The mini browser and the console update as you type, and each goal gets a check mark when it's done.

                    No clicking needed. Each goal gets a check mark by itself once your code does it.

                    1. Write something in the console with console.log. not done yet
                    2. Change the text of the #title heading using getElementById. not done yet
                    3. Change the .note paragraph using querySelector. not done yet
                    4. Add a new <li> to the #news list using appendChild. not done yet
                    Your code
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      Try an exercise

                      Recap

                      • The browser turns your HTML into a tree called the DOM. JavaScript changes the DOM, and the page on the screen follows.
                      • getElementById("name") finds the element with that id. querySelector(".class") finds the first element that matches a CSS selector. Both give back null when nothing matches.
                      • innerHTML reads or replaces what's inside an element. createElement makes a new element, and appendChild adds it to the page as the last child of a parent.

                      References

                      Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                      • WHATWG. DOM Standard (official specification). Open reference
                      • ECMA International. ECMAScript Language Specification (official specification). Open reference