JavaScript with Sean Doyle

Lesson 6: The Document Object Model (DOM)

The DOM

The Big 5 Concepts

  1. The browser copies the HTML document and creates a JavaScript object once the page has loaded.
  2. In this object, all of the elements, attributes and text become properties of the document object.
  3. We can access (get or set) any part of a web page through these properties.
  4. Additional properties and methods (functions) are also added to the document object.
  5. An “event” mechanism is also created that lets us program for “when” user events occur on the elements.

Code Samples

var document = {}; //The browser makes a copy of the HTML document and creates a JavaScript object. This object has additional properties and methods attached to it. It also has an events mechanism that lets us listen for browser events.

//One of the most important events is the onload event of the browser window object. We have to wait for this because this means the DOM is created and ready to go.
window.onload = pageReady; //This will call the pageReady function I created once the browser has finished loading the web page.

function pageReady(){
//Now, we can interact with the DOM, all of the elements, their values and attributes as a JavaScript object.

//Using the .getElementById() method of the document object, I can get an HTML element from the DOM and store it in a variable...
	var myHeading = document.getElementById("mainH1");
//myHeading is holding <h1 id="mainH1">Welcome to My Site</h1>

//As noted, we can get and set values for anything in the DOM by referencing the variable that is holding that element...
	myHeading.innerHTML = "Welcome to Our JavaScript Site!";//This will overwrite (set) the text inside the element we selected on the live web page.


//The event mechanism lets us program for "when" user events occur on the elements.  Below, we grab a button and a paragraph (hidden with styling), then add an event listener to call a function that will show the paragraph when the button is clicked...
	var myButton = document.getElementById("details_btn");
	var detailsParagraph = document.getElementById("details");
	
	myButton.onclick = showDetails;

	function showDetails(){
		detailsParagraph.style.display = "block";
	}

}//end of the pageReady function. Everything that needs to access the DOM needs to be inside this function.