Reader small image

You're reading from  Hands-on JavaScript for Python Developers

Product typeBook
Published inSep 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648121
Edition1st Edition
Tools
Right arrow
Author (1)
Sonyl Nagale
Sonyl Nagale
author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale

Right arrow
The Document Object Model (DOM)

The Document Object Model (DOM) is the API exposed by the browser to allow JavaScript to communicate with HTML and, indirectly, CSS. Since one of JavaScript's main abilities is dynamically changing content on a page, we should know how to do that. Enter the DOM.

In this chapter, we will learn how to use this powerful API to read and change content on a page. I'm sure you've seen websites that change content without reloading the page. These programs use DOM manipulation, and we'll learn how to use it.

The following topics will be covered in this chapter:

  • Selectors
  • Properties
  • Manipulations

Technical requirements

Using selectors

So far, we've only been using console.log and alerts and prompts to input and output information. While these methods are useful for testing, they're not exactly what you would use in everyday life. Most of the web applications that we use, from searching to email, use the DOM to interact with the user to get input and show information. Let's take a look at a small example: https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-6/hello.

If you open the HTML in the browser, we see a very simple page:

Figure 6.1 Our basic page

If we click the button, we don't get an alert or a console message, but instead, we have this:

Figure 6.2 An in-page response to our click!

Yay! It's our first instance of DOM manipulation.

DOM manipulation explained

Let's look at the JavaScript that powered that amazing example:

document.querySelector('button').addEventListener('click', (e) => {
document...

Properties

We've dealt with a few properties already: innerHTML of a node, src of an image, and id of a node. There is a vast array of properties available to us, so let's take a peek at how CSS marries with JavaScript.

Just for the sake of argument, let's change our Animals program to use JavaScript to change the background color of the target instead of CSS (https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-6/animals-2):

const images = {
'path': 'images/',
'dog': 'dog.jpg',
'cat': 'cat.jpg',
'elephant': 'elephant.jpg',
'horse': 'horse.jpg',
'panda': 'panda.jpg',
'rabbit': 'rabbit.jpg'
}

const buttons = document.querySelectorAll('.flex-item');

buttons.forEach((button) => {
button.addEventListener('mouseover', (e) => {
e.target.style.backgroundColor = ...

Manipulations

When working with the DOM via JavaScript, we can not only read but manipulate these properties. Let's get some practice in manipulating properties by making a small program: a sticky note creator.

Sticky note creator

We're going to make a sticky note creator that takes a color and a message and adds that colored box to the DOM with an ordinal number. Here's what our final product might look like:

Figure 6.9 Final product

Take a look at the starter code: https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-6/stickies/starter-code.

Your goal is to recreate this functionality. Here are two methods we haven't yet covered for you to research:

  • document.createElement()
  • container.appendChild()

Solution code

How did you do? Let's take a look at the solution code:

const container = document.querySelector('.container') // set .container to a variable so we don't need to find it every time we click...

Summary

Yay, we've finally gotten into the DOM and manipulated it! Congrats on where you're at so far!

With JavaScript, we can now dynamically change what is on the page as opposed to only using alerts and console messages. Here's an overview of what we learned:

  • querySelector and querySelectorAll are our gateways into the magical realm of the DOM.
  • The DOM exists only in memory as a dynamic representation of where the HTML was when the page was loaded.
  • Selectors for these methods will use CSS selectors; legacy methods will not.
  • Properties of nodes can be changed, but the nomenclature varies.

In the next chapter, we'll work more with events. Events are at the heart of a JavaScript program, so let's learn about their structure and use.

Questions

Consider the following code:

  <button>Click me!</button>

Answer the following question:

  1. What is the correct syntax to select the button?
    1. document.querySelector('Click me!')
    2. document.querySelector('.button')
    3. document.querySelector('#button')
    4. document.querySelector('button')

Take a look at this code:

<button>Click me!</button>
<button>Click me two!</button>
<button>Click me three!</button>
<button>Click me four!</button>

Answer the following questions:

  1. True or false: document.querySelector('button') will serve our needs to place a click handler on each button.
    1. True
    2. False
  2. To change the text of the button from "Click me!" to "Click me first!", what should we use?
    1. document.querySelectorAll('button')[0].innerHTML = "Click me first!"
    2. document.querySelector('button')[0].innerHTML = "Click me first!"
    3. document...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-on JavaScript for Python Developers
Published in: Sep 2020Publisher: PacktISBN-13: 9781838648121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale