JavaScript DOM : Building Rich User Interfaces

Understanding the Javascript DOM is crucial for web development. For web documents, the DOM is a programming interface. It offers a JavaScript interface for interacting with HTML and XML documents and depicts their structure.

We’ll dive into the JavaScript DOM in this guide, going over its foundations, methods of manipulation, and recommended practices.

What is Javascript DOM

The Javascript DOM is an object representation of the HTML elements. It acts as a bridge between your code and the user interface, and has a tree-like structure with parent and child relationships.

It consists of nodes, such as elements, attributes, and text, representing different parts of the document.

The Javascript DOM represents the hierarchical structure of HTML/XML documents as a tree of nodes. Each node corresponds to an element, attribute, or piece of text in the document. The Javascript DOM provides methods and properties to access, traverse, and modify this tree dynamically.

A programming interface for HTML (HyperText Markup Language) and XML (Extensible Markup Language) documents is called the Document Object Model (DOM). It specifies how a document is accessed and handled and its logical structure.

Because the Javascript DOM doesn’t identify any relationship between objects, it is a logical structure.

Javascript DOM is a method of representing the website in a hierarchically structured form, making it more straightforward for programmers and users to navigate the document.

Using the Javascript DOM, we may quickly access and modify HTML tags, IDs, classes, attributes, or elements using the Document object’s given commands or methods. JavaScript can access the web page’s HTML and CSS using the Javascript DOM and give HTML elements behavior. Therefore, Document Object Model is essentially an API that interacts with and represents HTML or XML documents.

Keypoints of Javascript DOM

  • Tree Structure: The DOM represents the web page’s structure as a hierarchy of nodes. Each node corresponds to an element, attribute, or text content in the document.
  • Access and Manipulation: Programmers can use programming languages like JavaScript to interact with the Javascript DOM. This enables them to access, modify, or delete elements and content on a web page dynamically.
  • Live Representation: The DOM is considered a live representation of the web document. When changes are made to the DOM using scripting, they are immediately reflected in the displayed web page.
  • Browser Interaction: Browsers use the DOM to render and display web pages. When a web page is loaded, the browser builds the DOM based on the HTML or XML document, and this DOM is then used for rendering and interactivity.
  • Cross-Language Compatibility: While JavaScript is the primary language used to interact with the Javascript DOM, other programming languages can also be used through various language bindings and APIs.

How Javascript DOM Works

JavaScript DOM (Document Object Model) works by providing a structured representation of HTML documents, which JavaScript can interact with dynamically. Here’s a simplified explanation of how it works:

  1. Parsing HTML: When a web page is loaded, the browser parses the HTML markup and constructs a tree-like structure known as the DOM tree. This tree consists of nodes representing elements, attributes, text, comments, etc.
  2. Accessing DOM Elements: JavaScript can access elements in the DOM tree using various methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll. These methods allow developers to select specific elements based on their IDs, classes, tags, or CSS selectors.
  3. Manipulating DOM Elements: Once elements are selected, JavaScript can manipulate them dynamically. This includes changing element attributes, modifying content, adding or removing classes, and altering styles. DOM manipulation enables developers to update the appearance and behavior of web pages in response to user interactions or application logic.
  4. Handling Events: JavaScript DOM allows developers to respond to user interactions or system events by attaching event listeners to DOM elements. Event listeners are functions that execute when specific events, such as clicks, mouse movements, key presses, or form submissions, occur on the associated elements.
  5. Updating Rendering: As JavaScript modifies the DOM, the browser updates the document’s visual representation to reflect the changes. This process involves re-rendering parts of the document affected by DOM manipulation, ensuring that the user sees the updated content and layout on the web page.

Example:

Let’s start with the following simple document:

<!DOCTYPE HTML> 
<html> 
<head> 
<title>Welcome to Dom</title> 
</head> 
<body> This is dom description. </body> 
</html>

The DOM represents HTML as a tree structure of tags. Here’s how it looks:

Javascript DOM Tree Structure

In the image provided, Each node in the tree represents an object.

Element nodes, referred to as elements, define the structure of the tree. For instance, <html> serves as the root, followed by its children <head> and <body>, and so on.

Text within elements creates text nodes, denoted as #text. A text node consists solely of a string, devoid of children, and always resides as a leaf in the tree.

For example, the <title> tag contains the text “Welcome to Dom”.

It’s important to acknowledge special characters within text nodes:

  • A newline: ↵ (recognized in JavaScript as \n).
  • A space: ␣

Spaces and newlines are valid characters, akin to letters and digits. They form text nodes and integrate into the DOM. In the aforementioned example, the <head> tag includes spaces preceding <title>, resulting in the creation of a #text node (containing only a newline and some spaces).

There are only two primary exceptions to note:

  1. Leading spaces and newlines before <head> are disregarded, a practice rooted in historical reasons.
  2. If content appears after </body>, it is automatically relocated within the body, positioned at the end. This aligns with the HTML specification mandating that all content must reside within <body>. Thus, no spaces should follow </body>.

Properties of DOM:

Let’s look at some of the document object’s properties that it has access to and can change.

Window Object:

The browser’s Window Object is always at the top of the hierarchy. It functions similarly to an API in that all of the browser’s properties and methods may be configured and accessed. The browser automatically creates it.

Properties of the window object include information about the window itself, such as its dimensions (innerWidth, innerHeight), location (location), history (history), and more.

Methods of the window object allow interaction with the browser window, such as opening new windows (open()), closing windows (close()), and setting timeouts (setTimeout()).

Document object:

A document object is created when an HTML document is loaded into a window. A number of the ‘document’ object’s properties refer to other things, allowing access to and altering the web page’s content. We always begin by accessing the ‘document’ object whenever we need to access any element on an HTML page. The window object has a document object as a property.

Form Object:

Form tags serve as their representation.

Properties of the form object include references to form elements within the form, such as elements, action, method, etc.

Methods of the form object allow actions like submitting the form (submit()), resetting the form (reset()), and accessing form data.

Link Object:

Link tags serve as their representation.

Properties of the link object include attributes of the <link> element, such as href, rel, type, etc.

The link object can be used to access and manipulate stylesheet links dynamically, for example, changing the stylesheet URL or disabling/enabling stylesheets.

Anchor Object:

A href tags are used to indicate it.

Properties of the anchor object include attributes of the <a> element, such as href, target, innerText, etc.

The anchor object allows manipulation of hyperlink properties, such as changing the link target or text dynamically.

Control Elements:

Control elements within forms, such as text fields, radio buttons, checkboxes, etc., are represented in the DOM as individual objects corresponding to their respective HTML elements.

Properties of control elements depend on their type and can include attributes such as value, checked, disabled, etc.

These objects allow dynamic interaction with form elements, such as setting or getting their values, enabling/disabling, or validating user input.

Methods of the document object

We can access and modify a document’s contents using its methods.

The following are some crucial document object methods:

getElementById(): This method allows you to retrieve an element from the document by its unique ID.

Syntax: document.getElementById(id)

Example: var element = document.getElementById(‘myElement’);

getElementsByClassName(): Retrieves a collection of elements that have a specific class name.

Syntax: document.getElementsByClassName(className)

Example: var elements = document.getElementsByClassName(‘myClass’);

getElementsByTagName(): Returns a collection of elements with the given tag name.

Syntax: document.getElementsByTagName(tagName)

Example: var paragraphs = document.getElementsByTagName(‘p’);

querySelector(): Returns the first element within the document that matches the specified CSS selector.

Syntax: document.querySelector(selector)

Example: var element = document.querySelector(‘.myClass’);

querySelectorAll(): Returns a static (not live) NodeList representing a list of elements that match the specified group of selectors.

Syntax: document.querySelectorAll(selector)

Example: var elements = document.querySelectorAll(‘.myClass’);

createElement(): Creates a new HTML element specified by the tagName.

Syntax: document.createElement(tagName)

Example: var newDiv = document.createElement(‘div’);

appendChild(): Adds a new child node to an element as the last child node.

Syntax: parent.appendChild(child)

Example: document.body.appendChild(newDiv);

removeChild(): Removes a child node from the DOM.

Syntax: parent.removeChild(child)

Example: document.body.removeChild(childElement);

setAttribute(): Sets the value of an attribute on the specified element.

Syntax: element.setAttribute(attribute, value)

Example: element.setAttribute(‘class’, ‘newClass’);

getAttribute(): Returns the value of the specified attribute on the element.

Syntax: element.getAttribute(attribute)

Example: var classValue = element.getAttribute(‘class’);

write(): Writes HTML expressions or JavaScript code to a document.

Syntax: document.write(text)

Example: document.write(“<h1>Hello, world!</h1>”);

writeln(): Similar to write(), but adds a newline character after the specified text.

Syntax: document.writeln(text)

Example: document.writeln(“<p>This is a paragraph.</p>”);

Credits:

Reference:

Conclusion:

An effective tool for developing dynamic and interactive online web applications is the JavaScript DOM. You may effectively edit web pages and produce captivating user experiences by being aware of its principles and adhering to best practices. Any web developer must understand the DOM to update content, process user input, and dynamically generate elements.

In conclusion, the Javascript DOM acts as a conduit between JavaScript and HTML/XML documents, allowing programmers to dynamically interact with and modify web content. You can fully utilize the Javascript DOM to create engaging online experiences if you have a firm grasp of its concepts and methods.