CS130: Spring 2020

Intro to the Web

CS130: Spring 2020

Lessons > Tutorial 5. JavaScript & the DOM: Part 2

Week 6: Tutorial

This week in tutorial, we will be doing a walkthrough of homework 3 in order to: (1) introduce and discuss some additional DOM properties (e.g. accessing sibling elements), and (2) introduce you to how you might want to use a variable to track the state of your program. Regarding item (2): in order for your browser to show you your next photo, you have to track what photo they’re currently viewing, and this requires using a variable.

Before you begin homework 3, please review the concepts below, and complete the exercises:

Step 1: Review the DOM Rules

What element do you want to target?

Use a document.querySelector("your_selector"), where the selector goes inside of the parenthesis. Recall: use a class selector, a tag selector, or an id selector

Do you want to change its style?

Then use this pattern:

document.querySelector("your_selector").style.some_property = some_value;

Note that you would replace your_selector, some_property and some_value with valid values. Refer to the cheatsheet from Tutorial 4 to see a list of some of the style properties.

Do you want to change its attribute?

Then use this pattern:

document.querySelector("your_selector").some_attribute = some_value;

Note that you would replace your_selector, some_attribute and some_value with valid values. Refer to the cheatsheet from Tutorial 4 to see a list of some common attributes.

  • nextElementSibling (docs)
  • previousElementSibling (docs)

Step 2: Complete the DOM exercises

  1. Open your JavaScript console
  2. Select the first h1 tag for this page.
    • modify its innerHTML
    • modify its font color
  3. Select the first img tag for this page.
    • modify its src attribute to point to another image (copy any image url that you find online).
    • update the innerHTML of the img element’s previousElementSibling
    • update the innerHTML of the img element’s nextElementSibling

Step 2: Start Homework 3

WHen you’re done from the above, please download and begin homework 3.