search
HomeWeb Front-endJS TutorialAn article on detailed operations on JavaScript DOM

This article brings you relevant knowledge about javascript, which mainly introduces related issues about the detailed operation of DOM, including what is DOM, what is DOM Tree, how to obtain DOM, etc. Let’s take a look at the content below, I hope it will be helpful to everyone.

An article on detailed operations on JavaScript DOM

[Related recommendations: javascript video tutorial, web front-end]

What is DOM?

Document Object Model, abbreviated DOM, Chinese: Document Object Model, is the standard programming interface## recommended by the W3C organization for processing extensible markup languages.

#What is DOM Tree?

DOM Tree refers to parsing the HTML page through DOM and generating The HTML tree tree structure and the corresponding access method, with the help of DOM Tree, we can directly and easily operate on the HTML page The content of each tag, such as the following HTML code

    <title>玩转dom</title>
    <p>我是一个dom节点</p>
    <p>
        </p><p>p p</p>
    
, is abstracted into a DOM tree as shown below:


An article on detailed operations on JavaScript DOM

After understanding the above knowledge, the following is the study of the API, I will explain from four aspects: how to get DOM, how to create and add DOM, how to modify DOM and how to delete DOM. Follow up

Get DOM

There are many APIs to get DOM, but It’s all very simple, come on


1. Get by id

Syntax:

document.getElementById("id name");
Example:

    <p>我是p节点</p>
    <script>
        var p = document.getElementById("p");
        console.log(p);
    </script>

An article on detailed operations on JavaScript DOM

Open the console and you can see that you have successfully obtained


2. Obtain via tag name

Syntax:

document.getElementsByTagName("tag name");
Example:

    <p>我是p节点</p>
    <p>我也是p节点</p>
    <script>
        var p = document.getElementsByTagName("p");
        console.log(p);
        for (let i = 0; i < p.length; i++) {
            console.log(p[i]);
        }
    </script>

An article on detailed operations on JavaScript DOM

Note: Use the getElementsByTagName() method to return a collection of objects with the specified tag name, because what we get is a collection of objects, so we want To operate the elements inside, you need to traverse. Note: The element object obtained using this method is dynamic


3. Obtain through the class name

Syntax:

document.getElementsByClassName("class name");
Example:

    <p>我是p节点</p>
    <p>我是p节点</p>
    <script>
        var p = document.getElementsByClassName("p");
        console.log(p);
        for (let i = 0; i < p.length; i++) {
            console.log(p[i]);
        }
    </script>

An article on detailed operations on JavaScript DOM

This is also very simple, just remember it


4. Obtain [Recommendation] through HTML5 new api

Grammar:

document.querySelector("详见实例");
document.querySelectorAll("详见实例");
Example:

    <p>我是p节点</p>
    <p>梨花</p>
    <p>信息</p>
    <script>
        // 通过标签名获取
        var p = document.querySelector("p");
        // 通过类名获取,记得加点
        var qname = document.querySelector(".name");
        // 通过id获取,记得加#
        var info = document.querySelector("#info");
        // 获取匹配到的所有元素,返回数组
        var all = document.querySelectorAll("p");
        console.log(p);
        console.log(qname);
        console.log(info);
        for (let i = 0; i < all.length; i++) {
            console.log(all[i]);
        }
    </script>

An article on detailed operations on JavaScript DOM

You can see that using the new API of html5 is very flexible, so I like it very much Using this, it is also recommended that you use

5. Special element acquisition

In addition, there are some special elements that have their own acquisition methods, such as body and html elements

Get the body element

Syntax:

document.body;
Example:

    <script>
        var body = document.body;
        console.log(body);
    </script>

An article on detailed operations on JavaScript DOM You can see that all the contents of the body element were successfully obtained


Get html element

Syntax:

document.documentElement;
Example:

    <script>
        var html = document.documentElement;
        console.log(html);
    </script>

An article on detailed operations on JavaScript DOM As you can see, the entire web page html has been obtained. OK, so far, getting the DOM has come to an end. Now let’s start learning to dynamically create and add DOM

Create and add DOM

To put it bluntly, operating DOM is the same as playing with data, adding, deleting, modifying and checking , and creating and adding is equivalent to adding. When we add data, we must first have the data, and then add it. The same is true for DOM operations. First, we must create the DOM, and then tell it where to add it. Finally, the operation is completed. Let’s learn below. How to create dom, and, how to add dom

Dynamicly create DOM

It’s very simple, don’t be afraid, haha

Syntax:

document.createElement("元素名");
Example:

If you want to dynamically create an element
p, you can write it like this. The same is true for other things. Draw inferences from one example

var p = document.createElement("p");
Dynamicly add DOM

There are two types of adding dom, according to It is used in various situations, one is to append at the end of the child element of the parent element, the other is to append after specifying the child element

Append at the end

Syntax:

node.appendChild(child);
Example:

    <p>
        <a>百度一下</a>
    </p>

    <script>
        var p = document.createElement("p");
        p.innerText = "我就是p"
        var p = document.querySelector("p");
        p.appendChild(p);
    </script>

An article on detailed operations on JavaScript DOM

动态创建元素p段落标签,并写入文字“我就是p”,最后获取p元素,并将p追加为p的孩子,这种追加方式是在末尾追加,因此效果如上图所示

指定元素后追加 

语法:

node.insertBefore(child, 指定元素);

实例:

    <p>
        <a>百度一下</a>
        <span>我是span弟弟</span>
    </p>

    <script>
        var p = document.createElement("p");
        p.innerText = "我就是p"
        var p = document.querySelector("p");
        var a = document.querySelector("a");
        // 在p下创建p,位置在a元素之前
        p.insertBefore(p, a);
    </script>

An article on detailed operations on JavaScript DOM

这就完了?对啊,你以为呢?是不是很简单呢,简单就对了,剩下的就是要多练习了,好,进入下一环节,如何修改 DOM 呢?

修改 DOM

总结如下:

An article on detailed operations on JavaScript DOM

例子1:获取页面的p标签,并将内容改为 “周棋洛”

    <p>
        </p><p></p>
    

    <script>
        var p = document.querySelector("p");
        p.innerText = "周棋洛";
    </script>

例子2:点击按钮生成百度的超链接

    <p>
        <button>点击生成百度超链接</button>
    </p>

    <script>
        function createBaidu() {
            var p = document.querySelector("p");
            var a = document.createElement("a");
            a.href = "https://www.baidu.com";
            a.innerText = "百度一下,你就知道";
            p.append(a);
        }
    </script>

An article on detailed operations on JavaScript DOM

例子3:点击按钮,p标签内文字颜色变绿,手动狗头

    <p>
        <button>点击变绿</button>
        </p><p>我一会就变绿</p>
    

    <script>
        function changeColor() {
            var p = document.querySelector("p");
            p.style.color = "green";
        }
    </script>

An article on detailed operations on JavaScript DOM

删除 DOM

node.removeChild() 方法从 DOM 中删除一个子节点,返回删除的节点

语法:

node.removeChild(child);

案例:

    <p>
        <button>点击移除p</button>
        </p><p>我是p,一会就时间到了</p>
    

    <script>
        function removeP() {
            var p = document.querySelector("p");
            var p = document.querySelector("p");
            p.removeChild(p); 
        }
    </script>

An article on detailed operations on JavaScript DOM

【相关推荐:javascript视频教程web前端

The above is the detailed content of An article on detailed operations on JavaScript DOM. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment