Intro to the
DOM & JQuery
Objectives
- Identify differences between the DOM and HTML.
- Explain the methods and use the DOM in javascript.
- Manipulate the DOM by using jQuery selectors and functions.
- Register and trigger event handlers for jQuery events.
Review
- Understand fundamental data types.
- Create and modify JavaScript objects.
- Understand how to use a constructor to create objects
Document Object Model
DOM
The Document Object Model (DOM) is a programming interface for HTML and XML documents.
It represents the page so that programs can change the document structure, style and content.
The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.
■ Basically the DOM is your webpage with all the resources attached needed to build that page represented as a tree/object
■ Good Reference Article: https://css-tricks.com/dom/
Basically, the DOM is a large object that describes the structure of our content - and we can use Object notation to access elements, css, and functions attached to the document Object!
Document.getElementById(String id)
Document.querySelector(String selector)
Document.querySelectorAll(String selector)
What can we do with "element"?
https://developer.mozilla.org/en-US/docs/Web/API/Element
Working with the DOM:
Codealong
We can manipulate the DOM in 3 different ways
Inline JavaScript
(least desirable)
<body onload="window.alert('welcome to my app!');">
Include script tags in our HTML documents
This technique is used primarily when generating content/properties through a back-end language. Try to avoid this if not necessary.
<html>
<head>
<script>
alert('Welcome to my app!');
</script>
</head>
<body>
</body>
</html>
Including the JavaScript file at the footer of our site
// run this function when the document is loaded
window.onload = function() {
// create a couple of elements in an empty HTML page
var main_heading = document.createElement("h1");
var heading_text = document.createTextNode("Hello dynamic world!");
main_heading.appendChild(heading_text);
document.body.appendChild(main_heading);
}
It is important to get used to falling in the habit of only doing DOM related manipulation only once our content has loaded
The above window.onload function adds a new element to our page through the following steps:
- We first create the new H1 element through the document.createElement method.
- We create the text through the createTextNode method.
- The text is added to the newly created H1 element.
- The H1 element is added to the body. Both steps 3 and 4 use the appendChild method to the respective element. Think of appendChild as an array of elements belonging to the element we are adding to.
<body>
<div id="hello">Hello world</p>
<ul id="gaCampuses">
<li>DC</li>
<li>NY</li>
<li>SF</li>
<li>LA</li>
<li>HK</li>
</ul>
</body>
// run this function when the document is loaded
window.onload = function() {
// Target items by id via the getElementById() method
var helloElem = document.getElementById("hello");
// We can access that element's css styles
// through the style property, and then accessing
// the css property through its camel-cased equivalent
helloElem.style.color = "red";
var campusesContainer = document.getElementById("gaCampuses");
// The getElementsByTagName() method returns a live
// HTMLCollection of elements with the given tag name.
var gaCampuses = campusesContainer.getElementsByTagName("li");
// We can iterate through the returned collection with a for loop
for (var i = 0; i < gaCampuses.length; i++) {
gaCampuses[i].style.backgroundColor = "red";
}
}
<form>
<input id="my-input" />
<input id="my-input-button" type="submit" value="Run button code"></submit>
</form>
window.onload = function() {
button = document.getElementById('my-input-button');
// Event parameter is the default object
// event that would have happened on user click
button.onclick = function(event) {
// The preventDefault() method lets us disable the
// default action, allowing us to override with our on functionality.
event.preventDefault();
MyApp.do_something("world");
};
};
// We can define things outside of the `window.onload` that are evaluated
// only when called.
MyApp = {};
MyApp.do_something = function(name) {
console.log("Hello " + name);
}
DOM Manipulation: Independent Practice
Complete the main.js file in js_dom_exercise folder:
-
When the user clicks the submit button, take the value they've typed into the input box and add it to the list (remember: appendChild!)
-
Also, when a new item is added to the list, clear the input box. (Hint: the value property of the input box, before anyone types in it, is the empty string.)
-
Bonus: When they click submit without typing anything, alert the user "you must type in a value!"
jQuery and the DOM: Introduction
The DOM's API (application programming interface) give us access to a couple of different methods that allow us to select elements from the DOM.
- document.getElementById retrieves a single element with a matching ID.
- document.getElementsByClassName retrieves an array of elements that match the given class.
- document.getElementsByTagName retrieves an array of elements that are of the given type.
Accessing the DOM with plain JS can often get verbose and clunky
That's where JQuery comes in!
jQuery is an open-source project that was released in 2006, and it's a widely used JavaScript library
We want to select only the li element with .specialList class
<ul>
<li class="specialList">Special list item!</li>
<li> Not Special List item!</li>
<li> Not Special List item!</li>
</ul>
JQuery makes it really easy!
$(".specialList li:first-child")
There are also a number of special methods on the 'jQuery Object' that you can call which will manipulate the DOM for all elements select by the query, at once. These methods can do things like:
- change styling
- add event listeners for specific events
- write brand new content (text and HTML) into the page
Augmenting JavaScript with jQuery
When reading the jQuery documentation, be sure to scroll through the whole document to ensure you're looking at the correct method signature.
Most jQuery methods change their behavior depending on the number of arguments they have when called
For example, have a look at .val().
Note in the table of contents that there are two method signatures, .val() and .val(value).
This is our hint that .val() can do two things.
.val() is getter on an element, but that .val(value) is a setter on an element
Common JQuery Methods
We can use jQuery to find elements, manipulate the returned elements, change styles, and add event listeners.
// Target item by id
$('#item');
// Target item(s) by class
$('.box')
// Target item(s) by tag
$('h2')
Or change .css!
// It is good practice to prefix items
// we have selected via jQuery with a $ in
// front of the variable name
var $item = $('#item');
// Setting the css property requires us to
// pass the property we are changing and the
// value we are changing it to as parameters (strings)
// in the css() method
$item.css('color', 'red');
However it is best practice to use addClass() and removeClass()!
We can update the internal html of an element with the html() method.
Whatever we pass through the method will replace the current content of the selected element.
var $item = $('#item');
// We can replace the content of the
// element either with text or with additional html.
var htmlContent = "<p>Hello world</p>";
$item.html(htmlContent);
jQuery also gives us access to many events making dealing with user interaction significantly easier.
var $button = $('#my-button');
// Most events we will work with will
// pass as the first parameter in the on() method
$button.on('click', function(event) {
event.preventDefault();
// Do something
});
Create a Checklist: Independent Practice
Complete the main.js app in the jquery_exercise folder.
You'll add the ability to complete tasks in your favorite things list:
- Using jQuery, add a "complete task" link at the end of each to-do item (i.e. each "favorite thing")
- When clicked, the link will cross out the current item (hint: add a class to the list that sets the text-decoration to line-through)
- Each new item added by the user needs to also have the "complete task" link at the end
Conclusion
- Uderstand how HTML parses and creates the object model, the DOM.
- Use selectors and methods to access and update HTML using the DOM.
- Register and trigger event handlers for jQuery events.
Homework:
99 Bottles of Beer
- Remember the 99 Bottles of Beer assignment? For this assignment, you'll be creating a website that programatically displays the lyrics to that song.
- You'll need to create both an .html file and a .js file
- In your HTML file, you'll want to have an unordered list (<ul>) that contains all of your lyrics
- Each line of the song should appear inside of a list item (<li>) within that unordered list
- Your JavaScript file should programatically append each line of the song to the page--no hard-coding lyrics in HTML!
Further Resources
Aug 8: Intro to theDOM & JQuery
By Jessica Bell
Aug 8: Intro to theDOM & JQuery
- 165