3.2 - JS + HTML

Connecting two technologies to create interactive pages!

Yesterday's lesson on Good vs. Bad Code.

Today's Lesson: 3.2 - JS + HTML

Each element placed in a HTML document becomes an "object" in the browser's memory. This is called the Document Object Model, or DOM. This allows the browser to manipulate and style specific elements. It also allows JavaScript to connect to, modify, delete, and create elements on the page.

Through JavaScript, we can "talk" to the document object. No more printing to the console (unless we want to)!

The big takeaways from today's lesson are:

  • document.getElementById("id") // Will return a handle of the first element found with the matching ID. This is why unique identifiers are so crucial.

  • document.getElementsByName("name") // Will return all elements with the matching name (more on that another time because it uses something called an Array).

  • To modify an HTML element, grab its handle and then modify it:

let paragraph = document.getElementById("p1");

paragraph.innerHTML = "New content for the 'p' element.";

There are many aspects of an element that you can change. Too many to teach but you can look them up! The main ones are innerHTML, innerText, textContent, and style. The rest you can learn later.

Example:

In-class demo recorded using Scrimba so you can play with the code yourself. (Note that some items (like buttons) do not render while the video is playing. But if you pause the video and click RUN yourself, the preview page renders properly.)

The DOM is a representation of the HTML document with child and parent element "objects". JavaScript has the ability to directly manipulate the DOM in real-time, creating a sense of interactivity that we don't normally see from a regular document.

For example, a Google Doc is an HTML page that is manipulated "on-the-fly" as the user interacts with it. This is done using JavaScript.

Today's Task

  • This one is purposefully quick. Fork this Repl and follow the instructions.

  • Hint - to add to the contents of a variable so that it isn't destroyed, you can do something like this:
    myVar = myVar + "stuff to add";

Today's RST Journal Entry:

  • You've had your first taste of programming. What have you learned? What was a struggle? What are you interested in?

    • What did you notice, what do you wonder?

  • Time to make your second journal entry for your RST portfolio. Any questions, just ask.