Home Web Front-end JS Tutorial Example 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           // 根据标签名获取标签集合
Copy after login
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  // 上一个兄弟标签元素
Copy after login
Indirect search

3. Operation elements

1. Content

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

2. Attributes

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

3.class operation

1 className               // 获取所有类名2 classList.remove(cls)                   // 删除指定类3 classList.add(cls)              // 添加类
Copy after login
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 class=&#39;c1&#39; href=&#39;https//www.baidu.com&#39;>百度</a>"
Copy after login
Create tag

b. Manipulate tag

 1 // 方式一 2 function AddEle1() { 3     //创建一个标签 4     //将标签添加到i1里面 5     var tag = "<p><input type=&#39;text&#39;></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 }
Copy after login
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";
Copy after login
样式操作

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
Copy after login
位置操作

7.提交表单

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

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

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                清除单次定时器
Copy after login
其他操作

 

四、事件

对于事件需要注意的要点

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);
Copy after login

函数在运行的瞬间生成一个活动对象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 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>test</title> 6 </head> 7 <body> 8     <div id="i1">欢迎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 </body>28 </html>
Copy after login
跑马灯
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 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 </head>33 <body>34     <div>35         <input id="o1" type="button" value="添加"/>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 id="i1" class="c1 hide"></div>61     <!-- 遮罩层结束 -->62  63     <!-- 弹出窗开始 -->64     <div id="i2" class="c2 hide">65         <p><input type="text"/></p>66         <p><input type="text"/></p>67         <p><input type="button" value="确认"/></p>68         <p><input id="o2" type="button" value="取消"/></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 </body>82 </html>
Copy after login
模态对话框
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>test</title> 6   7 </head> 8 <body> 9     <div>10         <input id="i1" type="button" value="全选"/>11         <input id="i2" type="button" value="取消"/>12         <input id="i3" type="button" value="反选"/>13         <table>14             <thead>15                 <tr>16                     <th>选择</th>17                     <th>主机名</th>18                     <th>端口</th>19                 </tr>20             </thead>21             <tbody id="tb">22                 <tr>23                     <td><input type="checkbox"/></td>24                     <td>1.1.1.1</td>25                     <td>190</td>26                 </tr>27                 <tr>28                     <td><input type="checkbox"/></td>29                     <td>1.1.1.2</td>30                     <td>192</td>31                 </tr>32                 <tr>33                     <td><input type="checkbox"/></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 </body>74 </html>
Copy after login
全选、反选、取消
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 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 </head>18 <body>19     <div style="width: 300px">20         <div class="item">21             <div id="i1" class="header" onclick="ChangeMenu(&#39;i1&#39;)">菜单1</div>22             <div class="content">23                 <div>内容1</div>24                 <div>内容1</div>25           &;bsp;     <div>内容1</div>26             </div>27         </div>28         <div class="item">29             <div id="i2" class="header" onclick="ChangeMenu(&#39;i2&#39;)">菜单2</div>30             <div class="content hide">31                 <div>内容2</div>32                 <div>内容2</div>33                 <div>内容2</div>34             </div>35         </div>36         <div class="item">37             <div id="i3" class="header" onclick="ChangeMenu(&#39;i3&#39;)">菜单3</div>38             <div class="content hide">39                 <div>内容3</div>40                 <div>内容3</div>41                 <div>内容3</div>42             </div>43         </div>44         <div class="item">45             <div id="i4" class="header" onclick="ChangeMenu(&#39;i4&#39;)">菜单4</div>46             <div class="content hide">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 </body>65 </html>
Copy after login
左侧菜单
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 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 </head>18 <body>19     <div style="width: 600px;margin: 0 auto">20         <input id="i1" type="text" value="请输入关键字"/>21         <input type="text" placeholder="请输入关键字" />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 </body>38 </html>
Copy after login
搜索框

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 of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PyCharm usage tutorial: guide you in detail to run the operation PyCharm usage tutorial: guide you in detail to run the operation Feb 26, 2024 pm 05:51 PM

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

What is sudo and why is it important? What is sudo and why is it important? Feb 21, 2024 pm 07:01 PM

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

What to do if you forget to press F2 for win10 boot password What to do if you forget to press F2 for win10 boot password Feb 28, 2024 am 08:31 AM

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

How to disable the action button on iPhone 15 Pro and 15 Pro Max How to disable the action button on iPhone 15 Pro and 15 Pro Max Nov 07, 2023 am 11:17 AM

Apple brought some Pro-exclusive hardware features to iPhone 15 Pro and 15 Pro Max, which attracted everyone’s attention. We're talking titanium frames, sleek designs, the new A17 Pro chipset, an exciting 5x telephoto lens, and more. Of all the bells and whistles added to the iPhone 15 Pro models, the action button remains a prominent and prominent feature. Needless to say, it is a useful addition to launching actions on your iPhone. That said, you could accidentally hold down the Action button and trigger the feature inadvertently. Frankly, it's annoying. To avoid this, you should disable the action button on iPhone 15 Pro and 15 Pro Max. let

Custom Action Buttons: Explore Personalization on iPhone 15 Pro Custom Action Buttons: Explore Personalization on iPhone 15 Pro Sep 24, 2023 pm 03:05 PM

Apple's iPhone 15 Pro and iPhone 15 Pro Max introduce a new programmable action button that replaces the traditional ring/silent switch above the volume buttons. Read on to learn what the Action button does and how to customize it. A new action button on Apple iPhone 15 Pro models replaces the traditional iPhone switch that activates Ring and Silent. By default, the new button will still activate both functions with a long press, but you can also have a long press perform a range of other functions, including quick access to the camera or flashlight, activating voice memos, focus mode, translation, and accessibility features like magnifier . You can also associate it with a single shortcut, opening up a ton of other possibilities

CSS web page scroll monitoring: monitor web page scroll events and perform corresponding operations CSS web page scroll monitoring: monitor web page scroll events and perform corresponding operations Nov 18, 2023 am 10:35 AM

CSS web page scroll monitoring: monitor web page scroll events and perform corresponding operations. With the continuous development of front-end technology, the effects and interactions of web pages are becoming more and more rich and diverse. Among them, scroll monitoring is a common technology that can perform some special effects or operations based on the scroll position when the user scrolls the web page. Generally speaking, scroll monitoring can be implemented through JavaScript. However, in some cases, we can also achieve the effect of scroll monitoring through pure CSS. This article will introduce how to implement scrolling of web pages through CSS

See all articles