How DOM Works in JavaScript

How DOM Works in JavaScript

How To Manipulate the DOM

The DOM, which stands for Document Object Model, is a table-like representation of a web page's structure. This layout makes viewing and editing a web page's content from the browser simple.

What Is the DOM?

The DOM is an abbreviation for Document Object Model. It is a programming interface for web documents that models the structure of an HTML or XML document as a tree, with each document's element acting as a node in the tree. Using computer languages like JavaScript, the DOM gives developers access to and control over the content and structure of a web page.

With the DOM, programmers can:

  • React to user inputs like keyboard and mouse clicks.

  • The page's elements can be added, removed, or changed.

  • Access and edit a web page's content, including the text, photos, and links.

  • Dynamically change a web page's content without refreshing the page entirely.

The DOM is a crucial component of web programming. All web browsers now support it.

Importance of DOM in a Website

Web documents have a programming interface called the Document Object Model (DOM). Since that software can alter the document's structure, appearance, and content, it represents the page. The DOM is significant because it allows dynamic, interactive web pages and applications.

The DOM is significant for the following reasons in particular:

  • Accessibility: Using the DOM, web content can be accessible to users with disabilities. Assistive technology tools like screen readers and magnifiers use the DOM to navigate and view web pages.

  • Interactivity: Web page interactivity is made possible by the DOM, which lets scripts and computer languages like JavaScript change a page's behaviour and content. With the DOM, programmers may make animations, react to user interaction, and dynamically change the website.

  • Cross-platform compatibility: Because the DOM is a standard interface, it is functional on various platforms and gadgets. This enables web application developers to construct programs that function flawlessly in different operating systems and browsers.

  • Content and presentation separation: The DOM offers a mechanism to divide a web page's content and presentation, making it simpler to maintain and update. Developers can alter the appearance of a page without changing the underlying content by utilizing CSS to style the display of the page.

The DOM is essential to creating contemporary web applications because it allows programmers to produce dynamic, interactive, and accessible web content.

Structure or Tree of a Web Page

A website's structure, sometimes called its "tree," describes how the pages and contents are arranged. Users may traverse the website and discover the information they need with the help of this layout. However, many other methods exist to structure a website. A hierarchical (arranged in order from the most to the least important) tree-like structure is one popular choice.

The homepage, which often offers connections to the primary sections of the site, is at the top of the hierarchy. Several of the subpages below the homepage are categorized or divided into sections. A layered order of pages can be created by further subdividing these sections

For instance, below is what a page structure will look like:

  • Body

    • nav

      • Home

      • About Us

      • Products

      • Services

      • Contact Us

  • Header

    • img

    • h1

    • p

  • Main

    • section

      • h1

      • div

        • img

        • p

Above, we have the body, which is the parent container. This is followed by the nav, header and main tags, which are the direct children container of the body. Within them is their child element.

The home, about us, product, services, and contact us are considered the child elements of the nav tag.

The header tag has img, h1 and p as its children elements.

The primary tag has just one child element—the section tag. The section tag, in turn, has h1 and div tags as its child element. And the div has the second img and p tags as its children components.

Accessing JavaScript Object Properties

There are two ways to access the javascript object property: dot and bracket notation.

  1. Dot notation: The dot notation is used to access the property of an object by using the property name after the dot. For example:
let person = {
  name: "Grace",
  age: 25,
  address: {
    city: "Port Harcourt",
    state: "Rivers State"
  }
};

console.log(person.name); // "John"
console.log(person.age); // 30
console.log(person.address.city); // "New York"
console.log(person.address.state); // ""
  1. Bracket notation: Bracket notation is used to access an object property by specifying the property name as a string inside square brackets.

    Example:

let person = {
  name: "Grace",
  age: 22,
  address: {
    city: "Uyo",
    state: "Akwa Ibom"
  }
};

console.log(person['name']); // "John"
console.log(person['age']); // 30
console.log(person['address']['city']); // "New York"
console.log(person['address']['state']); // "NY"

You can also use variables inside square brackets to access object properties dynamically.

Example:

let propName = 'name';
let propAge = 'age';
let person = {
  name: "Grace",
  age: 27
};

console.log(person[propName]); 
console.log(person[propAge]);// "John"

JavaScript DOM Selectors

Several DOM selectors can be used in JavaScript to choose and control items in an HTML document. Here are a few selectors that are frequently used:

  1. GetElementById: This selector selects an element with a specified ID.

     var element = document.getElementById("myId");
    
  2. GetElementsByClassName: This selector selects all ingredients with a specified class name.

     var elements = document.getElementsByClassName("myClass");
    
  3. GetElementsByTagName: This selector selects all ingredients with a specified tag name.

     var elements = document.getElementsByTagName("div");
    
  4. QuerySelector: This selector selects the first element that matches a specified CSS selector.

     var element = document.querySelector(".myClass");
    
  5. QuerySelectorAll: This selector selects all details that match a specified CSS selector.

     var elements = document.querySelectorAll("div.myClass");
    

    To pick elements based on CSS selectors, you may also use alternative selectors like querySelectorAll and querySelector. Once a component has been chosen, JavaScript allows you to change its characteristics, such as content or style.

Manipulating the DOM

An essential component of web development is working with the Document Object Model (DOM). A programming interface called the DOM gives programmers access to and control over the elements on a web page. Here are a few typical JavaScript DOM manipulation techniques:

  1. Changing Element Properties: With JavaScript, you can modify an element's properties after you've chosen it. For instance, you could alter a component's textual content, HTML markup, class, or style.

  2. Creating New Elements: You can create new elements using the createElement method and then add them to the page using the appendChild method.

  3. Removing Elements: You can remove elements from the page using the removeChild method.

  4. Responding to Events: You can add event listeners to elements using JavaScript. For example, you can add a click event listener to a button and perform some action when the button is clicked.

Overall, manipulating the DOM is a powerful way to create dynamic web pages that respond to user input and change over time. However, it's essential to use DOM manipulation judiciously and avoid excessive manipulation, as it can negatively impact performance and usability.

Conclusion

We have covered the different aspects of the DOM, how easy it makes the building process, and how a web page can be modified on the go.

As a programmer, you should try accessing the DOM and see how it can help you work better.

The journey to success is not a sprint but a marathon.

If you found this article helpful, please connect me on Twitter @helenefebe.