通过HTML DOM,可访问JavaScript HTML文档的所有元素。下面本篇文章就来给大家介绍一下,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

DOM能干啥?
● JavaScript 能够改变页面中的所有 HTML 元素
● JavaScript 能够改变页面中的所有 HTML 属性
● JavaScript 能够改变页面中的所有 CSS 样式
● JavaScript 能够对页面中的所有事件做出反应
【相关课程推荐:JavaScript视频教程】
当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。
HTML DOM 模型被构造为对象的树:

查找元素方法:
1、直接查找:
● getElementByid(): 通过 id 找到 HTML 元素
● getElementsByTagName(): 通过标签名找到 HTML 元素(列表)
● getElementsByClassName(): 通过类名找到 HTML 元素(列表)
● getelementsByName(): 通过name属性找到HTML元素(列表)
2、间接查找:
parentNode 父节点
childNodes 所有子节点
firstChild 第一个子节点
lastChild 最后一个子节点
nextSibling 下一个兄弟节点
previousSibling 上一个兄弟节点
parentElement 父节点标签元素
children 所有子标签
firstElementChild 第一个子标签元素
lastElementChild 最后一个子标签元素
nextElementtSibling 下一个兄弟标签元素
previousElementSibling 上一个兄弟标签元素3、添加删除节点和元素:
操作方法:
innerText 文本,指定ID下所有文本的拼接,去除间隔的HTML元素 outerText 写模式下,替换所有子元素 innerHTML 会根据指定的值创建新的 DOM 树,然后用这个 DOM 树完全替换调用元素原先的所有子节点。 outerHTML 写模式下,新的元素替换原有的 DOM 树 value 属性可设置或返回密码域的默认值。获取文本框的值。
Class属性操作(CSS样式表名):
className 获取所有类名 classList.remove(cls) 删除指定类 classList.add(cls) 添加类
checkbox属性:
checkbox.checked:true选中,false不选
tag标签操作:
1、createElement()创建标签:
每个HTML标签都有自己的属性,属性参照:https://www.w3school.com.cn/jsref/dom_obj_anchor.asp
function append_tag(){
var a = document.createElement('a')
var cur = document.getElementById('dd')
a.innerHTML='click me'
a.href='http://www.baidu.com'
a.className='a1'
cur.appendChild(a) //添加标签}\\----------等同于
var a_tag="<a class='a1' href='>click me</a>"2、操作标签:
insertAdjacentText('位置',obj) 在指定的地方插入文本内容,如果是HTML对象会以文本形式显示出来
insertAdjacentHTML('位置',obj) 在指定的地方插入html内容
位置说明:
beforeBegin:标签起始位置前(标签前) afterBegin:标签起始位置后(标签内) beforeEnd:标签结束位置前(标签内) afterEnd: 标签结束位置后(标签外)
3、标签样式操作style:
var obj = document.getElementById('i1') obj.style.fontSize = "32px"; obj.style.backgroundColor = "red";
4、位置操作
document.documentElement.offsetHeight 总文档高度 document.documentElement.clientHeight 当前文档占屏幕高度 tag.offsetHeight 自身高度 tag.offsetTop 距离上级定位高度 tag.offsetParent 父定位标签 tag.scrollTop 滚动高度
/*
clientHeight -> 可见区域:height + padding
clientTop -> border高度
offsetHeight -> 可见区域:height + padding + border
offsetTop -> 上级定位标签的高度
scrollHeight -> 全文高:height + padding
scrollTop -> 滚动高度
特别的:
document.documentElement代指文档根节点
*/事件:
addEventListener() 方法用于向指定元素添加事件句柄。
addEventListener() 方法添加的事件句柄不会覆盖已存在的事件句柄。
你可以向一个元素添加多个事件句柄。
你可以向同个元素添加多个同类型的事件句柄,如:两个 "click" 事件。
你可以向任何 DOM 对象添加事件监听,不仅仅是 HTML 元素。如: window 对象。
addEventListener() 方法可以更简单的控制事件(冒泡与捕获)。
当你使用 addEventListener() 方法时, JavaScript 从 HTML 标记中分离开来,可读性更强, 在没有控制HTML标记时也可以添加事件监听。
你可以使用 removeEventListener() 方法来移除事件的监听。
语法:
element.addEventListener(event, function, useCapture);
事件类型:
| Properties |
When did this event occur... | Properties | When did this event occur ... |
|---|---|---|---|
| onabort | The loading of the image was interrupted. | onload | A page or image is loaded. |
| onblur | The element loses focus. | onmousedown | The mouse button is pressed. |
| onchange | The content of the field is changed. | onmousemove | The mouse was moved. |
| onclick | Event handler called when the user clicks on an object. | onmouseout | The mouse moves away from an element. |
| ondblclick | Event handler called when the user double-clicks an object. | onmouseover | Move the mouse over an element. |
| onerror | An error occurred while loading the document or image. | onmouseup | The mouse button was released. |
| onfocus | The element gets focus. | onreset | The reset button is clicked. |
| onkeydown | A certain keyboard key was pressed. | onresize | The window or frame was resized. |
| onkeypress | A keyboard key is pressed and released. | onselect | The text is selected. |
| onkeyup | A certain keyboard key was released. | onsubmit | The confirmation button is clicked. |
| onunload | The user exits the page. |
键盘鼠标事件:
| 属性 | 描述 |
|---|---|
| altKey | 返回当事件被触发时,"ALT" 是否被按下。 |
| button | 返回当事件被触发时,哪个鼠标按钮被点击。 |
| clientX | 返回当事件被触发时,鼠标指针的水平坐标。 |
| clientY | 返回当事件被触发时,鼠标指针的垂直坐标。 |
| ctrlKey | 返回当事件被触发时,"CTRL" 键是否被按下。 |
| metaKey | 返回当事件被触发时,"meta" 键是否被按下。 |
| relatedTarget | 返回与事件的目标节点相关的节点。 |
| screenX | 返回当某个事件被触发时,鼠标指针的水平坐标。 |
| screenY | 返回当某个事件被触发时,鼠标指针的垂直坐标。 |
| shiftKey | 返回当事件被触发时,"SHIFT" 键是否被按下。 |
小例子:
1、文本框默认文字
<input id="i1" type="text" onfocus="foucs(this)" onblur="blurs(this)" value="请输入关键字"/>
<script>
function foucs(th){
var v=th.value;
if (v=='请输入关键字'){
th.value='';
}
}
function blurs(th){
var v=th.value;
if (v.length==0){
th.value='请输入关键字';
th.style.color="gray";
th.style.border="1px solid red";
}
}</script>2、添加标签
<div style="border: 1px solid red;" id="std"></div>
function b_b(){
var std=document.getElementById('std');
var new_b="<input type='button' value='我是beforeBegin,在DIV前' />";
std.insertAdjacentHTML('beforeBegin',new_b);}
function a_b(){
var std=document.getElementById('std');
var new_b="<input type='button' value='我是afterBegin,在DIV内前' />";
std.insertAdjacentHTML('afterBegin',new_b);}
function b_e(){
var std=document.getElementById('std');
var new_b="<input type='button' value='我是beforeEnd,在DIV后' />";
std.insertAdjacentHTML('beforeEnd',new_b);}
function a_e(){
var std=document.getElementById('std');
var new_b="<input type='button' value='我是afterEnd,在DIV内后'/>";
std.insertAdjacentHTML('afterEnd',new_b);}3、展开同时隐藏其它子菜单:
HTML:
<div id="left_menu" class="left_menu">
<div id='m1' class="main_menu" onclick="show_sub_menu(this)"><span>人员管理</span></div>
<div id='sm1' class="sub_menu">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</div>
<div id='m2' class="main_menu" onclick="show_sub_menu(this)"><span>组别管理</span></div>
<div id='sm2' class="sub_menu">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</div></div>js:
function show_sub_menu(th){
var parentId = th.id;
var childId='s'+parentId;
var childE=document.getElementById('left_menu').children;
for (var s in childE){
var e=childE[s].classList;
console.log(e);
if (e){
if (childE[s].id==childId){
childE[s].classList.add('show');
}else{
childE[s].classList.remove('show');
}
}
}}4、标签提交:
<!-- DOM提交标单!--><form id="f1" action="search.html">
<input id="input1" type="text"/>
<a onclick="a_submit()">提交吧</a></form><script>
function a_submit(){
document.getElementById('f1').submit();
}</script>5、html、css、js页面分离:生产环境的写法。
每类存储为单独的文件,其中js使用dom添加事件方法,可以html更简洁。
例子:鼠标移动表格行变色
HTML:
<table id='tb'>
<tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr></table>JS:给table添加属性和class
var t=document.getElementById('tb').classList;
t.add('tb_style');
var mytrs=document.getElementsByTagName('tr');
var td_numbers=mytrs.length;
for (var td=0;td<td_numbers;td++){
mytrs[td].onmouseover=function(){this.style.backgroundColor='red';};
mytrs[td].onmouseout=function(){this.style.backgroundColor='';};
}css
.tb_style{
bacground-color:pink;}6、词法分析:形参--》函数体内函数,编译时函数体内的函数会分配 内存地址,覆盖形参。
function cifa(age){
console.log(age); \\function age
age=22;
console.log(age); \\22
function age(){};
console.log(age); \\22}age(3)The above is the detailed content of Learn more about JavaScript's DOM. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding 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 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


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

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

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

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.






