Lesson 14: JavaScript Living Space - the Browser Environment

By Maria Antonietta Perna

As we have seen, the JavaScript language is made up of objects, their properties and methods. Your JavaScript code is interpreted and executed by a web browser. Therefore, JavaScript lives and comes alive in the browser environment.

This environment, in its turn, is also present in the JavaScript language, and obviously it is so in object form. Better yet, in the form of several objects, their properties and methods.

In this lesson you will be presented with a quick overview of the main objects making up the browser environment.

In particular, you will learn about:

  • the Browser Object Model (BOM);
  • the Document Object Model (DOM);
  • accessing, adding, and removing DOM elements and attributes.

What is the Browser Object Model (BOM)?

The BOM is a a collection of objects that represent the browser and the computer screen. These objects are accessible through the global objects window and window.screen.

The window object is global to the extent that it represents the very host environment of all other JavaScript objects. It's so fundamental, that you've already used it without needing to invoke it explicitly.

In fact, you already used alert() and onload. You didn't need explicitly to write window.alert() because the global window object was already presupposed.

Also, you could think about the window object as being at the top of a tree-like hierarchy of other objects, its descendants, or children. In fact, it's quite common for programming languages to use family-related metaphors to refer to objects representing their environment.

You will have occasion to work further with the window object through the rest of this tutorial. For now, let's move on to the Document Object Model (DOM).

What is the Document Object Model (DOM)?

One of the most interesting children of the window object, certainly from the point of view of JavaScript, is the Document object. This gives access to the all the elements that make up your HTML document.

The DOM is an ever evolving standard defined by the World Wide Web Consortium (W3C) implemented with varying degrees of consistency among different kinds of browsers. It contains a wealth of properties and methods that enable you to access and manipulate anything you can think of in an HTML document. So far you've used document.write() to write on the HTML page, and document.getElementById() to get a hook on an HTML element. But there's a lot more.

For example, here's all the info the document object can be made to yield when appropriately nudged. Insert the following code inside enclosing <script> tags of an HTML page and preview its content in a browser:

		
		//Set up your variables to represent
		
		//bits of info about your document:
		
		var myTitle = document.title;
		
		var myUrl = document.URL;
		
		var myLastModification = document.lastModified;
		
		var myInfoString = "The title of my document is: " + myTitle + "<br />";
		
		myInfoString += "My document's URL is: " + myUrl + "<br />";
		
		myInfoString += "My document was last modified on: " + myLastModification;
		
		document.write(myInfoString);
		
		

That's so cool. Let's have a look at how the HTML page is represented in the DOM.

What does a DOM representation of an HTML page look like?

The DOM represents HTML elements in a top-down tree-like structure. For instance, let's consider the following simple HTML document:

		
		<html>
		<head>
		<title>Lesson 14: DOM</title>
		</head>
		<body>
				
		<p>Lorem ipsum ...</p>
			
		<p>Lorem ipsum ...</p>
			
		<p>link <a href="http://html.net">HTML.net</a></p>
				
		</body>
		</html>
		
		

The DOM representation of the elements in the HTML page above is as follows:

Illustration: Graphical representation of the DOM relative to the HTML page above

The DOM elements are also known as nodes. Family-related metaphors are also used to represent the relationships and the position of each node with respect to the others. In connection to the DOM tree graphic above, we find:

  1. The <html> node

    The <html> element or node, is parent to all other nodes. In fact, all other DOM nodes are nested inside the <html> node;

  2. <head> and <body> nodes

    Next, we find 2 elements: the <head> and the <body>. These have a parent/child relationship with the <html> element (the parent). Because both are on the same level, they're siblings with respect to each other;

  3. <title> and <p> nodes

    The next level down is occupied by the <title> as child of the <head>, and 3 <p> elements as children of the <body>. In our sample HTML page above, <title> and <p> tags are siblings when considered with respect to each other;

  4. Text nodes

    The text inside the <p> tags, and the text inside the anchor tag are called text nodes. In this case they're children of the <p> element and the <a> element respectively;

  5. Anchor tag

    The next level down is occupied by an anchor tag, which is child to one of the <p> tags.

How do I access DOM elements?

Use one of the 2 following methods of the document object to access DOM elements.

Get the DOM element by its id attribute

The most widely used method of the document object to access DOM elements is certainly our old friend document.getElementById(elementId). This is the most appropriate way of accessing 1 HTML element at a time.

		
		var inputBox = document.getElementById("txtHello");
		
		alert(inputBox);
		
		//if you run this code in an HTML page containing
		
		//an input element called txtHello, you should see
		
		//[object HTMLInputElement] displayed in an alert box.
		
		

Get DOM elements by tag name

Another popular way of accessing DOM elements is by using their tag name in the HTML mark-up. This is a handy way of grabbing all HTML elements in one go that have a tag name in common, such as images, links, list items, etc. You can store a reference to these elements in an array and manipulate them via JavaScript.

For example, in an HTML page containing a list and 3 list items, you can access each list item and modify their color and background-color style properties by inserting the following code in enclosing <script> tags:

		
		//Retrieve all 3 list items and store them in an array
		
		var listElems = document.getElementsByTagName("li");
		
		//loop over each list item and access the style property
		
		for (var i = 0; i < listElems.length; i++)
		
		{
		
		//Notice how you write backgroundColor,
		
		//NOT background-color as you would in CSS:
		
		listElems[i].style.backgroundColor = "red";
		
		listElems[i].style.color = "white";
		
		}
		
		

Run your HTML page in the browser. You should see something like the page indicated by following the example link above.

How do I add DOM elements?

In previous lessons you used the practical and easy innerHTML property of an HTML element to add new stuff to your web page, be it new mark-up or new text.

However, innerHTML, although widely used, has not been recognized as a standard by the W3C. The DOM standard way to add new elements to an HTML page via JavaScript is done as follows. Enter the code below in enclosing <script> tags inside an HTML page:

		
		//First create a <p> element with createElement(element):
		
		var newParagraph = document.createElement("p");
		
		//Then add <p> to the <body> tag with appendChild():
		
		document.body.appendChild(newParagraph);
		
		//Now create the text that goes inside the new <p> element
		
		//with createTextNode():
		
		var newTextPara = document.createTextNode("Hello DOM standard");
		
		//Finally, add the new text inside the <p> tag:
		
		newParagraph.appendChild(newTextPara);
		
		

You can also add attributes to the newly created DOM nodes with setAttribute(attrType, attrName), and later retrieve them with getAttribute(attrType). Using the code snippet above, you can add an id called newParagraph to the newly created paragraph like so:

		
		var newParagraph = document.createElement("p");
		
		//setAttribute has 2 string arguments: the attribute we want to set
		
		//and the name we want to apply to the attribute.
		
		//Here we create an id attribute called newParagraph:
		
		newParagraph.setAttribute("id", "newParagraph");
		
		document.body.appendChild(newParagraph);
		
		var newTextPara = document.createTextNode("Hello DOM standard");
		
		newParagraph.appendChild(newTextPara);
		
		//getAttribute() has one string argument: the type of attribute
		
		//we want to retrieve:
		
		alert("The Id of the new paragraph is: " + newParagraph.getAttribute("id"));
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.

As you can see, there are at least 2 steps you need to take to insert fresh stuff inside an HTML page with JavaScript:

  1. create the new content: to do this you use either createElement(element) in case of an HTML tag, or createTextNode(text) in case of new text content;
  2. append the newly created DOM node to the appropriate location in the HTML document.

I know, it's a bit more involved than the straightforward innerHTML, but it's standard-compliant.

How do I remove DOM elements?

That's pretty simple stuff. First grab the DOM node you want to remove, then use removeChild(elementToRemove).

Prepare a simple HTML document with a <p> element and an input button like so:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 14: Delete DOM Element</title>
		</head>
		<body>
		<h1>Lesson 14: Delete DOM element</h1>
		
		<p id="remove">I'm going to be removed.</p>
				
		<input type="button" value="Delete paragraph" onclick="deleteParagraph()" />
			
		</body>
		</html>
		
		

Note that the onclick attribute of the button element contains a call to the deleteParagraph() function. Let's write this function inside enclosing <script> tags in the <body> of our HTML page:

		
		function deleteParagraph()
		
		{
		
		//retrieve the element you want to remove:
		
		var remove = document.getElementById("remove");
		
		//use removeChild(elementToRemove) to delete the element
		
		document.body.removeChild(remove);
		
		}
		
		

Save your work, run it in a browser, and click the button. You should see something like the page indicated by following the example link above: after you click the button the paragraph should be removed from the page.

Summary

In this lesson you got introduced to the concepts of Browser Object Model (BOM) and Document Object Model (DOM). You also learned a few methods of the document object to access, modify, add, and delete HTML elements in a standard-compliant manner.

Well done! It's time to take a break and get ready for the next lesson where you tackle your first real-world task: setting and retrieving cookies.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 13: JavaScript Objects: Arrays

Lesson 15: Useful Tasks (I) – Setting and Retrieving Cookies >>

cron