JS HTML DOM

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term “document” is used in the broad sense – increasingly, HTML and XML are being used as the ways of representing many different kinds of information that may be stored in diverse systems, and much of these would conventionally be seen as data rather than as documents.

With DOM, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions – in particular, the DOM interfaces for the internal subset and external subset have not yet been specified.

As a W3C specification, one important objective for the DOM is to provide a standard programming interface that can be used in a wide variety of environments and applications. DOM can be used with any programming language such as JavaScript.

When a web page is loaded, the web browser creates a Document Object Model of the web page.

The HTML DOM model is constructed as a tree of objects. See the sample web page along with its HTML DOM tree of objects below.

<html>

<head>
<title>Sample Page</title>
</head>

<body>
<h3>Heading</h3>
<p>This is a paragraph.</p>
</body>

</html>

The HTML DOM Tree of Objects

 

HTML DOM Programming Interface

The HTML DOM can be accessed with JS and here all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that we can get or set (such as modifying the content of an HTML element).

A method is an action that we can perform (such as adding or deleting an HTML element).

In the example below, getElementById() is a method, while innerHTML is a property.

<html>

<head>
<title>Sample Page</title>
</head>

<body>

<h3>DOM Example with JS</h3>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Hello from JS!";
</script>

</body>

</html>

 

Output:

DOM Example with JS

Hello from JS!

 

The getElementById() Method

The most usual technique  to access an HTML element (or tag) is to use the id of the element (or tag).

In the example mentioned above the getElementById() method uses id="test" to access the element (or tag).

 
The innerHTML Property

The easiest way to find the content of an element (or tag) is by using the innerHTML property.

This property is useful for getting or replacing the content of any HTML element, including <html> and <body>.​