Link Search Menu Expand Document

The document and window Objects

We are to the point where we can use JavaScript for its original purpose – as a client-side scripting language to interact with HTML.

PREREQUISITE: Build a multi-page HTML/CSS project

If you’ve never built a HTML/CSS project, click here.

The Document Object Model (DOM)

An HTML Document is comprised of HTML Elements. An element consists of an opening tag, content, and a closing tag. Frequently, the opening tag will have attributes, which are details that further define the look and behavior of the content.

HTML Element Diagram Source: https://en.wikipedia.org/wiki/HTML_element#Syntax

The Document Object Model (DOM) is an interface that contains an HTML document’s elements and their relationships. In JavaScript, this interface can be accessed with the built-in document object.

Here’s an example HTML document and its corresponding DOM.

<!DOCTYPE html>
<html>
  <head>
    <title>My title</title>
  </head>
  <body>
    <h1>A heading</h1>
    <a href="/">Link text</a>
  </body>
</html>

DOM Diagram Source: https://en.wikipedia.org/wiki/Document_Object_Model

DOM Methods

There are methods associated with the document object that allow programs to access individual elements and collections of elements from the DOM.

PropertyDescription
document.getElementById(value)Returns the element of that id.
document.getElementsByClassName(value)Returns a collection of elements that have that class.
document.getElementsByTagName(value)Returns a collection of elements of that tag.

The query selector methods do similar tasks to the above, but leverage CSS selectors to select elements. The method you use to select elements comes down to personal preference. I like to use these querySelector methods because of their versatility, so in this series, I will just use querySelector for consistency. You should still know the other methods because of their ubiquity.

PropertyDescription
document.querySelector(selector)Returns the first element that matches the selector.
document.querySelectorAll(selector)Returns a collection of all the elements that match the selector.
// Get an element: <tag id="top">content</tag>
// These two lines accomplish the same task
const byId = document.getElementById("top")
const byIdQuery = document.querySelector("#top")

// Get all elements: <tag class="blue">content</tag>
const byClass = document.getElementsByClassName("blue")
const byClassQuery = document.querySelectorAll(".blue")
// Just the first element that matches the selector
const byClassQueryFirst = document.querySelector(".blue")

// Get all elements: <p>content</p>
const byTag = document.getElementsByTagName("p")
const byTagQuery = document.querySelectorAll("p")
// Just the first element that matches the selector
const byTagQueryFirst = document.querySelector("p")

An HTML Element Object

Once you have an element selected and stored in a variable, you can perform operations on it by accessing and modifying its properties.

PropertyDescription
element.getAttribute(name)Get attribute by name.
element.innerHTMLGet/set the inner HTML of the element.
element.innerTextGet/set the inner text of the element.
element.setAttribute(name, value)Set attribute by name.
element.style.propertySet inline style.

Example 1

This example selects an anchor tag with an id and adds the following: an href attribute, the color green (inline style), and inner text with the site’s name.

REMEMBER: You can only have one <body>, so put the code below within your existing body element.

<body>
  <a id="meritLink"></a>
  <script>
    const meritLink = document.querySelector("#meritLink")
    meritLink.setAttribute("href", "https://meritacademy.tech")
    meritLink.style.color = "#00ff00"
    meritLink.innerText = "Merit Academy Tech"
  </script>
</body>
Result
HTML
<a id="meritLink" href="https://meritacademy.tech" style="color: #00ff00;">
  Merit Academy Tech
</a>
Rendered Content

Merit Academy Tech

Example 2

This example adds two items to a list by selecting the <ul> element and appending to its innerHTML. In JavaScript, you need to put your HTML in strings.

<body>
  <h1>Favorite Foods</h1>
  <ul></ul>

  <script>
    const ul = document.querySelector("ul")
    ul.innerHTML += "<li>Pizza</li>"
    ul.innerHTML += "<li>Pineapple</li>"
  </script>
</body>
Result
HTML
<body>
  <h1>Favorite Foods</h1>
  <ul>
    <li>Pizza</li>
    <li>Pineapple</li>
  </ul>
</body>
Rendered Content

Favorite Foods

  • Pizza
  • Pineapple

DOM Practice

Visit https://www.w3schools.com/js/js_htmldom_methods.asp to see another example of the above.

The Window Object (Part 1)

The built-in window object contains information and actions related to the browser window. Here are some helpful properties, for a full list, click here.

PropertyDescription
window.close()Closes the current page.
window.innerHeightReturns the height of the viewport.
window.location.hrefReturns the full URL to the current page.
window.location.reload()Refreshes the current page.
window.scrollTo(x, y)Scroll to a position in the document.

Try these window properties out yourself in a project or the developer console.

Example 3 - Use a template string to add lots of HTML to the body

This example makes use of a template string (Made with \`, backticks, which are on the same key that ~ is). You can insert variables into a template string with ${}. Also, you can get the body of the HTML document with document.body.

<body>
  <script>
    document.body.innerHTML = `
      <h1>How tall are we?</h1>
      <p>The height of this page is ${window.innerHeight}px.</p>
    `
  </script>
</body>
Result (for a window of height 714px)
HTML
<body>
  <h1>How tall are we?</h1>
  <p>The height of this page is 714px.</p>
</body>
Rendered Content

How tall are we?

The height of this page is 714px.

Practice Task: Same Navigation

For multi-page projects that have the same navigation component on each page, it’s cumbersome to copy and paste the same navigation HTML to each page, let alone try to make a change later if needed. Proper web apps generate the navigation in some way (usually server-side) to keep the code DRY (Don’t Repeat Yourself). This project will have you generate the navigation for all pages client-side in a script.js file.

Create a HTML5 project with the following file structure:

index.html
page1.html
page2.html
script.js

Each HTML file should have the following for the <body>:

<body>
  <nav id="topNav"></nav>
  <p>Here is a link to this page: <a id="permalink"></a></p>
  <script src="script.js"></script>
</body>

Here’s a example boilerplate for this project: https://replit.com/@buckldav/NavigationGenerationStarter.

In script.js

  • Select the #topNav and using it’s innerHTML attribute, add a working <a> element for each HTML file.
  • Select the #permalink and set to href attribute to link to whatever page it’s on (using the window object). Also, the innerText of the #permalink element should be the same as the href.
    • For example, on page1.html, the site should say (replacing yourdomain.com with whatever your project’s domain is) – Here is a link to this page: https://yourdomain.com/page1.html.
Hints

Use window.location.href to get the URL to the current page.

After selecting the #permalink, use element.setAttribute() to set the href of the link.