The Document Object Model (DOM)

The designers of JavaScript were very smart. Rather than just creating yet another scripting language (which would still have been a pretty good improvement at the time), they had the vision to build it around the Document Object Model, or DOM. This breaks down the parts of an HTML document into discrete objects, each with its own properties and methods and each subject to JavaScript’s control.

JavaScript separates objects, properties, and methods using a period (one good reason why + is the string concatenation operator in JavaScript, rather than the period). For example, let’s consider a business card as an object we’ll call card. This object contains properties such as a name, address, phone number, and so on. In the syntax of JavaScript, these properties would look like this:

card.name
card.phone
card.address

Its methods are functions that retrieve, change, and otherwise act on the properties. For instance, to invoke a method that displays the properties of object card, you might use syntax such as:

card.display()

Have a look at some of the earlier examples in this chapter, where the statement document.write is used. Now that you understand how JavaScript is based around objects, you will see that write is actually a method of the document object.

Within JavaScript, there is a hierarchy of parent and child objects. This is what is known as the Document Object Model (see Figure 13-3).

Figure 13-3. Example of DOM object hierarchy

The figure uses ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.