Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Last active May 25, 2017 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewman12/9b78a4ec59688e43f1151818373c1cf2 to your computer and use it in GitHub Desktop.
Save jnewman12/9b78a4ec59688e43f1151818373c1cf2 to your computer and use it in GitHub Desktop.
WDI SM Intro to the DOM

Intro to the DOM

Students will be able to...

  • Explain what the DOM is
  • Use JavaScript to select parts of the DOM
  • Use JavaScript to change parts of the DOM

What is the DOM?

From MDN:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content.


Starter

Let's go crazy! Mess up the New York Times! Turn Google into Bing!

As a browser loads a page, it creates a representation of that page in which each element is an object. This representation is called the DOM tree, and it is stored in the browser's memory.


Selecting Elements

Before we get started, let's learn a bit about how to query the DOM w/ javascript. This is important, because javascript gives us all the tools we need to do DOM manipulation. We just have to learn some new methods.

What do we select by??

In javascript we have a bunch of ways to select elements. That's great, but for the most part, we only want to use a few. Let's look at a couple ways we can easily query the DOM.

document.getElementById

  • Returns a reference to the element by its ID; the ID is a string which can be used to uniquely identify the element, found in the HTML id attribute. If nothing is found, returns null.

     var titleEl = document.getElementById('title');
     console.log(titleEl);
  • Notice in this, we do not pass in the #. we only use the string

document.getElementsByClassName

  • Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
document.getElementsByClassName('test');
console.log(test);

document.getElementsByTagName

  • Returns an HTMLCollection of elements with the given tag name.
var pTags = document.getElementsByTagName('p');
console.log(pTags);

document.querySelector

  • Returns the first Element within the document that matches the specified selector, or group of selectors. Returns null if no matches are found; otherwise, it returns the first matching element.
var elem = document.querySelector(".myclass");
console.log(elem);

document.querySelectorAll

  • Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

Changing or modifying elements

  • So we saw some common ways to grab elements, but not change them. Now lets see how to change either the elements content or style (apperance).

innerHTML

  • The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants. Using this, we can both read an elements inner HTML and we can write to it or modify it.
var div = document.getElementById('content')
console.log(div.innerHTML); // => returns whatever the text of that content is
div.innerHTML = 'some new text';

style

  • The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.The style property has the same (and highest) priority in the CSS cascade as an inline style declaration set via the style attribute.
var elem = document.getElementById('opening');
elem.style // => returns stuff 
elem.style.color = 'red';

or

```js
var titleEl = document.getElementById('title');
titleEl.style.textAlign = 'center';
```

Iterating over a collection of elements

  • Like we saw earlier, iterating is very important. However, even tho these return array "like" objects, they are not arrays. Here is a way we can loop through selected elements.

  • Unfortunately, both HTMLCollection and nodeList do not have a forEach method to iterate over its elements.

  • A for loop works well because you can use the looping variable, such as i, to index into the list using square bracket notation:

     for(var i = 0; i < comments.length; i++) {
     	console.log(comments[i]);
     }

Let's use JS to 'grab' part of the DOM

Go to the class repo and copy the starter code into your workspace.

Open index.html in Chrome and then open the dev tools (command + option + i). Type these commands into the console and discuss the data type of the results with a partner.

  • document.getElementsByTagName('h1')
  • document.getElementsByClassName('info')
  • document.getElementById('content')

Now let's use JS to CHANGE some of the attributes of these elements.

  • if we want to change the text of the element, we can grab the element and change its innerHTML property.
  • if we want to change the CSS of an element, we can grab the element and change its style.color or its style.width

BONUS ROUND! Let's use JS to add an event listener to an object...

There are three ways to do it

  • In HTML: <element onclick="myFunction()">

  • In JavaScript: object.onclick=function(){myScript};

  • In JavaScript using the addEventListener() method: object.addEventListener('click', myFunction);

When the happy/sad face is clicked, make a pop up window appear saying how happy you are now that you know how to manipulate the DOM.

Conclusion

  • What data type results from each of these methods?
    • document.getElementsByTagName()
    • document.getElementsByClassName()
    • document.getElementById()
  • How would you select the second h1 on a page?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment