Document Object Model (DOM) in JavaScript

Document Object Model (DOM) in JavaScript

1. What is DOM

DOM Document Object Model is a programming interface for HTML and XML documents. It uses a logical tree to represent a document. The end point of each branch of the tree is a node . Each node contains objects , allowing elements to be created, changed, or deleted from the document. Events can also be added to these elements to make the page more dynamic.

DOM treats an HTML document as a tree of nodes, where a node represents an HTML element. The following HTML code is provided to better understand the DOM tree structure.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>DOM Object Model</h1>
        <h2>DOM tree structure</h2>
    </body>
</html>

The document is called the root node and contains one child node, <html> element. The <html> element contains two child elements, namely the <head> and <body> elements.

Both <head> and <body> have their own child elements, as shown below:

These elements in the document can be accessed and changed via JavaScript . The following will introduce how to use JavaScript to manipulate DOM .

2. Select elements

How to select elements in a document? There are several different ways to select elements in an HTML document. Here are three of them:

  • getElementById(): Returns an element matching a specific ID.
  • querySelector(): Returns the first HTMLElement object in the document that matches the specified selector or selector group.
  • querySelectorAll(): Returns a list of elements in the document that match the specified selector group (using a depth-first, pre-order traversal of the document's nodes).

3. getElementById()

In HTML, id is the unique identifier of an HTML element, which means that you cannot set the same id for two different elements. You must ensure that the id is unique throughout the document.

In JavaScript , you can get the HTML tag by using its id name.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>DOM Object Model</h1>
        <h2>DOM tree structure</h2>
        <p id="intro">DOM stands for Document Object Model, which is a programming interface. </p>

        <script type="text/javascript">
            const elemIntro = document.getElementById("intro");
            console.log(elemIntro);
        </script>
    </body>
</html>

Open the developer tools:

If you need to get the text content of an object, you can use textContent or innerText :

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>DOM Object Model</h1>
        <h2>DOM tree structure</h2>
        <p id="intro">DOM stands for Document Object Model, which is a programming interface. </p>

        <script type="text/javascript">
            const elemIntro = document.getElementById("intro");
            console.log(elemIntro);
            // Get the text content within the element const elemText = elemIntro.textContent; // elemIntro.innerText 
            console.log(elemText);
        </script>
    </body>
</html>

Open the controller to view:

4. querySelector()

Use this method to find elements with one or more CSS selectors. The following takes the National Day movie schedule information as an example to get the corresponding title and list elements through querySelector() .

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul class="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>

        <script type="text/javascript">
            const elemTitle = document.querySelector("h1");
            const elemList = document.querySelector(".movies");
            console.log("h1");
            console.log(elemTitle);
            console.log("ul movies");
            console.log(elemList);
        </script>
    </body>
</html>

Open the document in the browser and turn on the developer tools, you can see the following effect:

5. querySelectorAll()

This method finds all elements that match the CSS selector and returns a list of nodes. Let's find every li element of the movie schedule:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul class="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>

        <script type="text/javascript">
            const elemTitle = document.querySelector("h1");
            const movieItems = document.querySelectorAll(".movies > li");
            console.log(movieItems);
        </script>
    </body>
</html>

The effect of console printing is as follows:

The above node list can be traversed as follows:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul class="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>

        <script type="text/javascript">
            const elemTitle = document.querySelector("h1");
            const movieItems = document.querySelectorAll(".movies > li");
            movieItems.forEach((item) => {
                console.log(item);
            });
        </script>
    </body>
</html>

The effect of console printing is as follows:

6. Add new elements

How do you add new elements to a document? You can use document.createElement() to add a new element to the DOM tree and use textContent to add content to the new element. The following example adds a new movie schedule to the list of movie schedules:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul class="movies" id="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>

        <script type="text/javascript">
            const movieItems = document.getElementById("movies");
            const newMovie = document.createElement("li");
            newMovie.textContent = "The Eagle Catches the Chicken";
            movieItems.appendChild(newMovie);
        </script>
    </body>
</html>

After running, the page effect is as follows:

7. Change CSS styles

How to change inline CSS styles? By using the style attribute, you can change the CSS style in the HTML document. Taking the National Day movie schedule as an example, change the font size and font color of the page title h1 element:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul class="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>

        <script type="text/javascript">
            const pageTitle = document.querySelector("h1");
            pageTitle.style.fontSize = "24px";
            pageTitle.style.color = "#0000FF";
        </script>
    </body>
</html>

After running, the page effect is as follows:

Regarding the attributes of CSS styles, camelCase is used in JavaScript. For example, the corresponding attribute of font-size in JavaScript is fontSize , and background-color is backgroundColor .

8. How to monitor events

How to use events of elements on the page? Using the addEventListener() method, the following example adds a new movie schedule to the list by clicking a button, as follows:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM tree structure</title>
    </head>
    <body>
        <h1>2021 National Day movie schedule</h1>
        <ul id="movies">
            <li>Changjin Lake</li>
            <li>My Fathers and I</li>
            <li>Railway Heroes</li>
        </ul>
        <button id="addNew">Add the movie "Eagle Catches Chicken"</button>
        <script type="text/javascript">
            const moviesList = document.getElementById("movies");
            const button = document.getElementById("addNew");
            const addNewMovie = (movieTitle, elemTarget) => {
                const newMovie = document.createElement("li");
                newMovie.textContent = movieTitle;
                newMovie.style.color = "#ff0000";
                elemTarget.appendChild(newMovie);
            };
            button.addEventListener("click", () => {
                addNewMovie("The Eagle Catches the Chicken", moviesList);
            });
        </script>
    </body>
</html>

After running, the page effect is as follows:

In actual projects, event monitoring and processing are more complicated than this. For modern WEB development, rich front-end frameworks have already encapsulated event processing very well, and even make developers forget the relevant knowledge of event monitoring, such as event bubbling, event capture, event delegation, etc., which will not be expanded in this article.

in conclusion:

DOM Document Object Model, a programming interface for HTML and XML documents. When a browser first reads (parses) an HTML document, it creates a large object, a very large object based on the HTML document. This is the DOM. It is a tree structure modeled from HTML. DOM is used to interact and modify DOM structure or specific elements or nodes.

This is the end of this article about the Document Object Model DOM in JavaScript . For more relevant JavaScript Document Object Model DOM content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Document Object Model DOM
  • JavaScript Dom Object Operations
  • All properties of JavaScript variable Dom object
  • Example of how to access a specified node in a DOM object using JS
  • A brief discussion on how to read custom attributes of DOM objects (tags) using JS
  • Detailed explanation of common attribute methods of document objects in DOM in js basics
  • Detailed explanation of the attribute methods of element objects in DOM in js basics
  • JavaScript implements DOM object selector
  • JavaScript DOM Objects in-depth understanding
  • JavaScript - DOM Operation - Detailed Explanation of Window.document Object
  • jQuery objects and JavaScript objects, i.e. DOM objects, are converted to each other
  • js object relationship diagram facilitates dom operation
  • JavaScript DOM object learning example code
  • Detailed explanation of JavaScript operations on DOM objects

<<:  MySQL Flush-List and dirty page flushing mechanism

>>:  Solve the problem of docker container exiting immediately after starting

Recommend

Example code for implementing stacked carousel effect with HTML+CSS+JS

Effect: When the slideshow moves in one direction...

How to use binlog for data recovery in MySQL

Preface Recently, a data was operated incorrectly...

Improvement experience and sharing of 163 mailbox login box interactive design

I saw in the LOFTER competition that it was mentio...

Solutions to problems using addRoutes in Vue projects

Table of contents Preface 1. 404 Page 1. Causes 2...

Count the list tags in HTML

1. <dl> defines a list, <dt> defines ...

How to redirect PC address to mobile address in Vue

Requirements: The PC side and the mobile side are...

Native js implements shopping cart logic and functions

This article example shares the specific code of ...

How to clear mysql registry

Specific method: 1. Press [ win+r ] to open the r...

Linux operation and maintenance basic swap partition and lvm management tutorial

Table of contents 1. Swap partition SWAP 1.1 Crea...

Detailed explanation of nginx request header data reading process

In the previous article, we explained how nginx r...

Example of implementing TikTok text shaking effect with CSS

In daily development, front-end students often ar...