Page Content

Posts

What the Document Object Model Works in JavaScript

Document Object Model in JavaScript

While working with JavaScript on web pages, you must grasp the core idea of the Document Object Model, or DOM. The interface through which JavaScript communicates with HTML content in browser windows is its definition. To put it simply, the DOM gives JavaScript programs access to a web page’s structure and content so they may read or change it. As a live data structure, the DOM is updated instantly to reflect changes made with JavaScript, allowing the page to be seen on the screen. For the creation of dynamic web pages that react to user input rather than staying static, this feature is essential.

Visualising the DOM as a logical tree is crucial to understanding it. The browser automatically creates this page representation after downloading and analysing it. The DOM represents HTML and XML nested elements as a tree. Like an HTML page, the browser’s data structure is nested boxes or tags. Branching patterns let this data structure incorporate connected subelements. Structured hierarchically.

This tree is made up of separate parts known as nodes. There is a place for everything on the page in this organisational chart. Nodes stand in for the various sections of an HTML document. Everything else comes from the document node, which is the primary node. The root element node, which often represents the <html> tag, is located directly beneath the document node in HTML pages.

There are several types of nodes in the DOM tree:

  • Document node: Represents the entire HTML document.
  • Element nodes: Represent the HTML elements or tags, such as <html>, <head>, <body>, <p>, <div>, etc..
  • Text nodes: Represent the text content within elements.
  • Attribute nodes: Represent the attributes associated with elements.
  • Comment nodes: Represent HTML comments in the document.

The relationships between DOM nodes are often explained using family tree terms. With the exception of the root node, each node’s parent node is in its immediate vicinity. A node enclosed in another is its child. Nodes have several offspring. The same parent has siblings. Those above a node at any level are its ancestors, while those below it are its descendants.

Here is an example HTML snippet and its tree representation:

<html>
  <head>
    <title>Tab in the browser</title>
  </head>
  <body>
    <h1>DOM</h1>
    <div>
      <p>Hello web!</p>
      <a href="https://google.com">Here's a link!</a>
    </div>
  </body>
</html>

In the tree representation of this HTML:

  • <html> is the root element, a child of the document node (not shown in snippet, but implied as the highest level).
  • <head> and <body> are children of <html>. They are also siblings.
  • <head> has one child: <title>.
  • <body> has two children: <h1> and <div>. These are siblings.
  • <div> has two children: <p> and <a>. These are siblings.

As children of their respective components, text nodes would be used to represent text content such as “Hello web!” inside the <p> tag or “Here’s a link!” inside the <a> tag.

JavaScript HTML DOM Elements

At the top of this tree structure, beneath the document node, lies the outermost element, HTML. This logical tree is one of the attributes that comprise a web page’s DOM. Inherently, intricate web pages have intricate trees.

The document object, a globally accessible representation of the DOM, is used by JavaScript to communicate with this tree structure. The document object has numerous properties and methods that let programmers manipulate the page’s elements. Console.dir(document) allows you to examine the document object and its properties in the browser’s console.

The first step in utilising JavaScript to alter a webpage is to find or pick the particular element you wish to alter. The DOM offers several ways to do this. Selecting components by their id property using document is one of the most used methods.Using the document’s tag name, getElementById().retrieveElementsByTagName(), using the document’s class name.either by using CSS selectors with document or by using getElementsByClassName().paper and querySelector().the querySelectorAll function.

Following selection, JavaScript can add, remove, or alter HTML content and attributes, as well as read or edit an element’s characteristics, including its text content using textContent. Additionally, JavaScript can change an element’s style.

Here is a simple JavaScript example demonstrating how to select an element by its tag name and change its text content:

<!doctype html>
<html>
<head>
  <title>JS Tester</title>
</head>
<body>
  <h1>Test</h1>
  <script>
    // Select the h1 element
    const output = document.querySelector('h1'); // Using querySelector 
    // Change its text content
    output.textContent = "Hello World"; // Using textContent property
  </script>
</body>
</html>

The way JavaScript works with the DOM tree (in this case, the h1 node) to change the visible page content is demonstrated by this script, which chooses the <h1> element and changes its text to “Hello World.”

What are the attributes in JavaScript?

In addition to tags and text, HTML can include attributes. Providing attributes changes the element. The element’s opening tag’s attributes are assigned a value using name=”value” format. Values are usually in quotes.

For instance, the href element is used by the <a> tag, which indicates a hyperlink, to provide the destination URL to which the link will redirect. The behaviour of the an element is changed by the value of the href attribute.

Some important and commonly used HTML attributes include:

  • id: Gives an element a unique ID, used for selection.
  • class: Adds metadata used for styling (CSS) or manipulation (JavaScript).
  • src: Specifies the source for elements like images (<img>) or scripts (<script>).
  • style: Allows adding inline CSS styles directly to an element.
  • value: Sets the initial value for elements like buttons or input fields.

You can utilise attributes in JavaScript. HTML has special features that trigger JavaScript on user clicks or page loads. Examples include Onclick, Onload, Onfocus, Onblur, and Onchange. HTML5 also added data properties, allowing JavaScript to read and alter any data.

DOM is the browser’s representation of HTML material after parsing. The DOM represents HTML as a tree of nodes. In this tree, element nodes represent HTML tags and text nodes represent text content. The DOM has attribute representations. JavaScript’s DOM tree interaction lets it read, update, add, and remove elements and their properties, making web pages dynamic.

Here is a simple HTML snippet demonstrating elements and attributes:

<!DOCTYPE html>
<html>
<head>
<title>HTML Example</title>
</head>
<body>
<h1 id=”main-header”>Hello, HTML!</h1>
<p class=”intro-text”>This is a paragraph with some text.</p>
<a href=”https://developer.mozilla.org” target=”_blank”> </a>
</body>
</html>

In this example:

  • <html>, <head>, <title>, <body>, <h1>, <p>, and <a> are elements.
  • <!DOCTYPE html> is part of the HTML declaration.
  • id=”main-header”, class=”intro-text”, href=”https://developer.mozilla.org”, and target=”_blank” are attributes influencing their respective elements.

Here is a simple JavaScript example showing interaction:

<!doctype html>
<html>
<head>
<title>JS Interact</title>
</head>
<body>
<h1 id=”greeting”>Original Header</h1>
<a id=”mylink” href=”http://oldurl.com”> </a>

<script>
// Select the h1 element by its ID
const headerElement = document.getElementById(‘greeting’); // Supported by

// Change the text content of the h1 element
headerElement.textContent = “New Header Text!”; // Example usage based on exercise

// Select the link element by its ID
const linkElement = document.getElementById(‘mylink’);

// Get the current value of the ‘href’ attribute
const currentHref = linkElement.getAttribute(‘href’); // Supported by
console.log(“Current link href:”, currentHref); // Outside source interaction, but standard practice

// Set a new value for the ‘href’ attribute
linkElement.setAttribute(‘href’, ‘http://newurl.com’); // Supported by

// Set a new attribute, like a class
linkElement.setAttribute(‘class’, ‘updated-link’); // Supported by example

</script>
</body>
</html>

This code shows how JavaScript can pick components by id, update their text content, and manipulate properties like href and class using getAttribute and setAttribute.

In conclusion, the DOM is a logical tree structure of nodes that serve as an object-oriented representation of an HTML document. The browser creates it automatically, and it acts as the interface through which JavaScript may access, navigate, select, and modify items to build dynamic and interactive web pages.

Index