search
HomeWeb Front-endJS TutorialExample analysis on DOM operations

Example analysis on DOM operations

Jun 26, 2017 pm 01:38 PM
operate

1. Introduction

Document Object ModelDOM is a programming interface for HTML and XML documents. It provides a structured representation method for documents that can change the content and presentation of documents. What we are most concerned about is that the DOM connects web pages with scripts and other programming languages. The DOM belongs to the browser rather than the core content specified in the JavaScript language specification.

2. Search for elements

1. Directly search for

##
1 document.getElementById         // 根据ID获取一个标签2 document.getElementsByName      // 根据name属性获取标签集合3 document.getElementsByClassName         // 根据class属性获取标签集合4 document.getElementsByTagName           // 根据标签名获取标签集合
Direct search

2.Indirect search

 1 parentNode          // 父节点 2 childNodes          // 所有子节点 3 firstChild          // 第一个子节点 4 lastChild           // 最后一个子节点 5 nextSibling         // 下一个兄弟节点 6 previousSibling     // 上一个兄弟节点 7    8 parentElement           // 父节点标签元素 9 children                // 所有子标签10 firstElementChild       // 第一个子标签元素11 lastElementChild        // 最后一个子标签元素12 nextElementtSibling     // 下一个兄弟标签元素13 previousElementSibling  // 上一个兄弟标签元素
Indirect search

3. Operation elements

1. Content

1 innerText   // 文本2 outerText  
3 innerHTML   // HTML内容4 outerHTML5 value       // 值
Content operation

2. Attributes

1 attributes                                      // 获取所有标签属性2 setAttribute(key,value)                 // 设置标签属性3 getAttribute(key)                          // 获取指定标签属性
Attribute operation

3.class operation

1 className               // 获取所有类名2 classList.remove(cls)                   // 删除指定类3 classList.add(cls)              // 添加类
class operation

4. Tag operation

a.Create tag

1 // 方式一2 var tag = document.createElement("a");3 tag.innerText = "百度";4 tag.className = "c1";5 tag.href = "6   7 // 方式二8 var tag = "<a>百度</a>"
Create tag

b. Manipulate tag

 1 // 方式一 2 function AddEle1() { 3     //创建一个标签 4     //将标签添加到i1里面 5     var tag = "<p><input></p>"; 6     //beforeBegin、afterBegin、beforeEnd、afterEnd 7     document.getElementById("i1").insertAdjacentHTML("beforeEnd",tag); 8 } 9  10 // 方式二11 function AddEle2() {12     //创建一个标签13     //将标签添加到i1里面14     var tag = document.createElement("input");15     tag.setAttribute("type", "text");16     tag.style.fontSize = "16px";17     tag.style.color = "red";18  19     var p = document.createElement("p");20     p.appendChild(tag);21     document.getElementById("i1").appendChild(p);22 }
Operation tag
Note that the first parameter can only be "beforeBegin", "afterBegin", "beforeEnd", "afterEnd"

5. Style operation

1 var obj = document.getElementById("i1");2 obj.style.fontSize = “32px”;3 obj.style.backgroundColor = "red";
样式操作

6.位置操作

 1 总文档高度 2 document.documentElement.offsetHeight 3   4 当前文档占屏幕高度 5 document.documentElement.clientHeight 6   7 自身高度 8 tag.offsetHeight 9  10 距离上级定位高度11 tag.offsetTop12  13 父定位标签14 tag.offsetParent15  16 滚动高度17 tag.scrollTop
位置操作

7.提交表单

任何标签通过DOM都可以提交表单

1 document.getElementById("form").submit()
提交表单

8.其他操作

 1 console.log     输出框 2 alert           弹出框 3 confirm         确认框 4   5 // url和刷新 6 location.href           获取url 7 location.href = "url" 重定向 8 location.reload()       重新加载 9  10 // 定时器11 setInterval                 多次定时器12 clearInterval               清除多次定时器13 setTimeout                  单次定时器14 clearTimeout                清除单次定时器
其他操作

 

四、事件

对于事件需要注意的要点

this

event

事件链以及跳出

this标签当前正在操作的标签event封装了当前事件的内容。

绑定事件方式

1.直接标签绑定 onclick="xxx()"

2.先获取Dom对象然后进行绑定

document.getElementById("xx").onclick

document.getElementById("xx").onfocus

this当前触发事件的标签

1.第一种绑定方式

function ClickOn(self){

// self 当前点击的标签

} 

2.第二种绑定方式

document.getElementById("xx").onclick = function(){

// this 代指当前点击的标签

}

3.第三种绑定方式捕捉 冒泡

addEventListener("click", function(){}, false)

addEventListener("click", function(){}, true)

 

、JavaScript词法分析

1 function t1(age){:2   console.log(age);3   var age = 27;4   console.log(age);5   function age(){};6   console.log(age);7 }8 t1(3);

函数在运行的瞬间生成一个活动对象Active Object简称AO

第一步分析参数

1.函数接收形式参数添加到AO的属性中并且这个时候值为undefined即AO.age=undefined

2.接收实参添加到AO的属性覆盖之前的undefined此时AO.age=3

第二步分析变量声明

1.如何上一步分析参数中AO还没有age属性则添加AO属性为undefined即AO.age=undefined

2.如果AO上面已经有age属性了则不作任何修改AO.age=3

第三部分析函数声明

如果有function age(){}把函数赋值给AO.age覆盖上一步分析的值

结果应该是

function age(){}

27

27

 

六、示例

 1 nbsp;html> 2  3  4     <meta> 5     <title>test</title> 6  7  8     <div>欢迎xxx莅临指导</div> 9     <script>10         function func() {11             // 根据ID获取标签内容12             var tag = document.getElementById("i1");13             // 获取标签内部的内容14             var content = tag.innerText;15             // 获取字符串第一个字符16             var f = content.charAt(0);17             // 获取字符串第二至末尾的全部字符18             var l = content.substring(1, content.length);19             // 拼接新的标签内容20             var new_content = l + f;21             // 修改标签内部的内容22             tag.innerText = new_content;23         }24         // 设置计时器25         setInterval("func()", 500);26     </script>27 28 
跑马灯
 1 nbsp;html> 2  3  4     <meta> 5     <title>test</title> 6     <style> 7         .hide{ 8             display: none; 9         }10         .c1{11             position: fixed;12             top: 0;13             right: 0;14             bottom: 0;15             left: 0;16             background-color: #000000;17             opacity: 0.5;18             z-index: 9;19         }20         .c2{21             width: 500px;22             height: 400px;23             background-color: #ffffff;24             position: fixed;25             top: 50%;26             left: 50%;27             margin-top: -200px;28             margin-left: -250px;29             z-index: 10;30         }31     </style>32 33 34     <div>35         <input>36         <table>37             <thead>38                 <tr>39                     <th>主机名</th>40                     <th>端口</th>41                 </tr>42             </thead>43             <tbody>44                 <tr>45                     <td>1.1.1.1</td>46                     <td>190</td>47                 </tr>48                 <tr>49                     <td>1.1.1.2</td>50                     <td>192</td>51                 </tr>52                 <tr>53                     <td>1.1.1.3</td>54                     <td>193</td>55                 </tr>56             </tbody>57         </table>58     </div>59     <!-- 遮罩层开始 -->60     <div></div>61     <!-- 遮罩层结束 -->62  63     <!-- 弹出窗开始 -->64     <div>65         <p><input></p>66         <p><input></p>67         <p><input></p>68         <p><input></p>69     </div>70     <!-- 弹出窗结束 -->71     <script>72         document.getElementById("o1").onclick = function () {73             document.getElementById("i1").classList.remove("hide");74             document.getElementById("i2").classList.remove("hide");75         }76         document.getElementById("o2").onclick = function () {77             document.getElementById("i1").classList.add("hide");78             document.getElementById("i2").classList.add("hide");79         }80     </script>81 82 
模态对话框
 1 nbsp;html> 2  3  4     <meta> 5     <title>test</title> 6   7  8  9     <div>10         <input>11         <input>12         <input>13         <table>14             <thead>15                 <tr>16                     <th>选择</th>17                     <th>主机名</th>18                     <th>端口</th>19                 </tr>20             </thead>21             <tbody>22                 <tr>23                     <td><input></td>24                     <td>1.1.1.1</td>25                     <td>190</td>26                 </tr>27                 <tr>28                     <td><input></td>29                     <td>1.1.1.2</td>30                     <td>192</td>31                 </tr>32                 <tr>33                     <td><input></td>34                     <td>1.1.1.3</td>35                     <td>193</td>36                 </tr>37             </tbody>38         </table>39     </div>40     <script>41         document.getElementById("i1").onclick = function () {42             var tb = document.getElementById("tb");43             var tr_list = tb.children;44             for(var i=0;i<tr_list.length;i++){45                 var current_tr = tr_list[i];46                 var checkbox = current_tr.children[0].children[0];47                 checkbox.checked = true;48             }49         };50         document.getElementById("i2").onclick = function () {51             var tb = document.getElementById("tb");52     &bsp;       var tr_list = tb.children;53             for(var i=0;i<tr_list.length;i++){54                 var current_tr = tr_list[i];55                 var checkbox = current_tr.children[0].children[0];56                 checkbox.checked = false;57             }58         };59         document.getElementById("i3").onclick = function () {60             var tb = document.getElementById("tb");61             var tr_list = tb.children;62             for(var i=0;i<tr_list.length;i++){63                 var current_tr = tr_list[i];64                 var checkbox = current_tr.children[0].children[0];65                 if(checkbox.checked) {66                     checkbox.checked = false;67                 }else{68                     checkbox.checked = true;69                 }70             }71         };72     </script>73 74 
全选、反选、取消
 1 nbsp;html> 2  3  4     <meta> 5     <title>test</title> 6     <style> 7         .hide{ 8             displa: none; 9         }10         .item .header{11             height: 35px;12             background-color: #2459a2;13             color: #ffffff;14             line-height: 35px;15         }16     </style>17 18 19     <div>20         <div>21             <div>菜单1</div>22             <div>23                 <div>内容1</div>24                 <div>内容1</div>25           &;bsp;     <div>内容1</div>26             </div>27         </div>28         <div>29             <div>菜单2</div>30             <div>31                 <div>内容2</div>32                 <div>内容2</div>33                 <div>内容2</div>34             </div>35         </div>36         <div>37             <div>菜单3</div>38             <div>39                 <div>内容3</div>40                 <div>内容3</div>41                 <div>内容3</div>42             </div>43         </div>44         <div>45             <div>菜单4</div>46             <div>47                 <div>内容4</div>48                 <div>内容4</div>49                 <div>内容4</div>50             </div>51         </div>52     </div>53     <script>54         function ChangeMenu(nid) {55             var current_header = document.getElementById(nid);56             var item_list = current_header.parentElement.parentElement.children;57             for(var i=0;i<item_list.length;i++){58                 var current_item = item_list[i];59                 current_item.children[1].classList.add("hide");60             }61             current_header.nextElementSibling.classList.remove("hide");62         };63     </script>64 65 
左侧菜单
 1 nbsp;html> 2  3  4     <meta> 5     <title>test</title> 6     <style> 7         .hide{ 8             display: none; 9         }10         .item .header{11             height: 35px;12             background-color: #2459a2;13             color: #ffffff;14             line-height: 35px;15         }16     </style>17 18 19     <div>20         <input>21         <input>22     </div>23     <script>24         document.getElementById("i1").onfocus = function () {25             var val = this.value;26             if(val == "请输入关键字"){27                 this.value = "";28             }29         }30         document.getElementById("i1").onblur = function () {31             var val = this.value;32             if(val == ""){33                 this.value = "请输入关键字";34             }35         }36     </script>37 38 
搜索框

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The 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 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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.