The Document Object Model (DOM) is a standard programming interface recommended by the W3C organization for processing extensible markup language (HTML or XML).

W3C has defined a series of DOM interfaces through which the content, structure and style of web pages can be changed.
1. For JavaScript, in order to enable JavaScript to operate HTML, JavaScript has its own DOM programming interface;
2. For HTML, DOM makes HTML form a DOM tree, including documents, elements, and nodes.
Document: The entire page is a document;
Element: All tags in the page are called elements;
Node: All content on the page is a node. Document node (ducument object), element node (element object), attribute node (attribute object), text node (text object) , comment node (comment object), The line break between codes is also a node.
All DOM elements we obtain are an object.

For DOM operations, we mainly focus on elements Operations mainly include create, add, delete, modify, check, attribute operations, and event operations.
1. Creating
mainly includes three types:
1. document.write
Features: If the page document flow is loaded (that is, all codes are executed), calling this sentence again will cause the page to be redrawn (That is, a new html page is created for us, and everything we wrote before is gone). (Rarely used)
2. innerHTML: Writing content to a DOM node will not cause the entire page to be redrawn.
3. createElement: It will not cause the page to be redrawn.
InnerHTML and createElement efficiency comparison:
①innerHTML splicing efficiency test:
<script>
function fn() {
var d1 = +new Date();
var str = '';
for (var i = 0; i < 1000; i++) {
document.body.innerHTML += '<div style="width:100px; height:2px; border:1px solid blue;">';
}
var d2 = +new Date();
console.log(d2 - d1);
}
fn();
</script>
The execution results are as follows



##The execution speed is about 1600 milliseconds
②createElement efficiency test
<script>
function fn() {
var d1 = +new Date();
for (var i = 0; i < 1000; i++) {
var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '2px';
div.style.border = '1px solid red';
document.body.appendChild(div);
}
var d2 = +new Date();
console.log(d2 - d1);
}
fn();
</script>
The execution results are as follows



执行速度为十几秒
③innerHTML数组效率测试
<script>
function fn() {
var d1 = +new Date();
var array = [];
for (var i = 0; i < 1000; i++) {
array.push('<div style="width:100px; height:2px; border:1px solid blue;">');
}
document.body.innerHTML = array.join('');
var d2 = +new Date();
console.log(d2 - d1);
}
fn();
</script>
执行结果如下



执行速度为个位数秒
结果分析:
执行效率:innerHTML数组效率 > createElement效率 > innerHTML拼接效率
所以创建多个元素时innerHTML效率更高(不要拼接字符串,采用数组形式拼接),结构稍微复杂麻烦一些。
createElement()创建多个元素时效率稍微低一些,但结构清晰。
二、增
主要包括两种:
1、appendChild:node.appendChild(child)是在后面追加元素
2、insertBefore:node.insertBefore(child)是添加到最前面
三、删
removeChild:node.removeChild(child)删除父节点中的一个子节点,并返回被删除的节点。
四、改
主要是修改dom元素的属性,dom元素的内容、属性,表单的值等。
1、修改元素属性:src、href、title等。可以直接修改,这些属性都是可读写的。
2、修改普通元素内容:innerText、innerHTML。(两者都是可读写的)
element.innerText:读取时,只读取标签里面的内容,不会少文字,但不会读取里边的标签、空格和换行。(非标准)
element.innerHTML:读取时,整个读取出来,包括html标签,同时保留空格和换行。(W3C标准,常用)
3、修改表单元素:value(表单里边的内容)、type(表单类型)、disabled(是否被使用)等。
4、修改元素样式:style、className。可以直接通过style修改属性,如果需要修改的属性较多或者为了方便操作,建议修改className。
五、查
主要获取查询dom的元素
1、DOM提供的API方法:getEementById、getElementsByTagName等古老的方法。
2. New methods provided by H5: querySelector, querySelectorAll. (Advocate)
3. Use node operations to obtain elements: parent (parentNode), child (children), brother (previousElementSibling, nextElementSibling). (Advocate)
6. Attribute operation
Main For custom attributes
1, setAttribute: Set the attribute value of dom. element.setAttribute('attribute', 'value'); Mainly for custom attributes
##2. getAttribute: Get the attribute value of dom
There are two ways to get the attribute value of dom: element.attribute and element.getAttribute('attribute')
Difference:
element.Attribute gets the built-in attribute value (the attribute that comes with the element itself);
element.getAttribute('attribute') mainly gets the Custom attributes (attributes added by ourselves).
3. removeAttribute: Remove the attribute. removeAttribute('attribute')
7. Event operation
give The element registers an event, taking: event source. event type = event handler
onclick: left mouse button click event.
onmouseover: Triggered when the mouse passes over.
onmouseout: Triggered when the mouse leaves.
onfocus: Triggered by getting mouse focus.
onblur: Triggered when mouse focus is lost.
dblclick: Left mouse button double-click event.
onmousemove: Triggered by mouse movement.
onmousedown: Triggered when the mouse button is pressed.
onmouseup: Triggered when the pressed mouse button is released.
Recommended learning: JavaScript video tutorial
The above is the detailed content of A brief discussion on DOM core operations in JavaScript. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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 WorksApr 14, 2025 am 12:05 AMThe 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 ImplementationsApr 13, 2025 am 12:05 AMDifferent 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 WorldApr 12, 2025 am 12:06 AMJavaScript'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)Apr 11, 2025 am 08:23 AMI 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)Apr 11, 2025 am 08:22 AMThis 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
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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),






