Table of Contents
根节点: documentElement 和  body
代码名称
同样提示下document.body不能为undefined. 在DOM的世界里, 一个元素找不到或者没有这个元素, 值都是为null的.
孩子元素
childNodes
children
Children 连接关系
firstChild 和   lastChild
parentNode ,  previousSibling 和  nextSibling
浏览器总是保持正确的连接关系.
总结
编程的人正在在线培训
"前端编程开发","后端开发","移动开发"等,
需要学习的可以加入群或者微信留言
原创内容,转载请注明出处.
公众微信号:bianchengderen
QQ群: 186659233
欢迎大家传播与分享.
Home Web Front-end HTML Tutorial DOM之行走在DOM中_html/css_WEB-ITnose

DOM之行走在DOM中_html/css_WEB-ITnose

Jun 21, 2016 am 08:51 AM

访问DOM都要从document开始. 这个对象提供了一系列的搜索和改变元素的方法.

根节点: documentElement 和  body

DOM的根节点是 document.documentElement .  这个特定的属性用来访问最顶端的HTML标签.

另外的开始点是document.body, 代表了BODY标签.

两者作为进入点都是有效的. 但是document.body可以为null.

例如, 在HEAD里script脚本访问document.body, 这时候会讲null来代替这个属性的值. 这是自然的, 因为这时候没有BODY标签.

在下面的例子中, 弹出框会输出null:

代码名称

<!DOCTYPE HTML><html>    <head>        <script>            alert("Body from HEAD: "+document.body) // null        </script>    </head>    <body>        <div>The document</div>         <script>            // different browsers output different text here,             // because of different implementations of toString              alert("Body from inside body: " + document.body)         </script>    </body></html>
Copy after login

同这个相反, document.documentElement总是有效的.

同样提示下document.body不能为undefined. 在DOM的世界里, 一个元素找不到或者没有这个元素, 值都是为null的.

一个更直观的描述上面的规则就是在脚本执行的时候, 引用的元素还没有被浏览器渲染.

孩子元素

有一些方式获取元素的孩子元素.

childNodes

一个元素引用他们的孩子节点,用childNodes来访问, 返回的是一个节点数组.

所有的节点被引用访问, 包含空白节点(除了IE < 9).

代码名称

<!DOCTYPE HTML><html>  <body>    <div>Allowed readers:</div>    <ul>      <li>Bob</li>      <li>Alice</li>    </ul>     <!-- a comment node -->     <script>        function go() {        var childNodes = document.body.childNodes         for(var i=0; i<childNodes.length; i++) {            alert(childNodes[i])        }      }    </script>     <button onclick="go()" style="width:100px">Go!</button>   </body></html>
Copy after login

SCRIPT节点同样包含在其中.

在上面的例子中, document.body.childNodes[1]是DIV元素(在所有的除了IE<9的浏览器). 在老版本的IE中, 他们没有空白节点, 因此 document.body.childNodes[1]是UL.

children

有时候我们仅需要浏览元素节点, 跳过文本节点. 这时候我们就该用children属性.

他包含所有的元素. 我们来看看统一的一个例子, 但是用children来代替childNodes.

他在这里将会输出的是所有的标签元素.

代码名称

<!DOCTYPE HTML><html>  <body>    <div>Allowed readers:</div>    <ul>      <li>Bob</li>      <li>Alice</li>    </ul>     <!-- a comment node -->     <script>        function go() {        var children = document.body.children         for(var i=0; i<children.length; i++) {            alert(children[i])        }      }    </script>     <button onclick="go()" style="width:100px">Go!</button>   </body></html>
Copy after login

Children 连接关系

通过或一系列的孩子元素还不够, 因为访问他们还不够方便.

因此, 还有其他的属性, 比如siblings, parent等等.

firstChild 和 lastChild

firstChild和lastChild属性可以快速访问第一个和最后一个孩子元素.

他们是基于同样的一致性的childNodes索引.

代码名称

var body = document.body alert(body.firstChild === body.childNodes[0])alert(body.lastChild === body.childNodes[body.childNodes.length-1])
Copy after login

parentNode , previousSibling 和 nextSibling

  • parentNode 属性引用到父节点. document.documentElement的父节点为null

  • previousSibling和nextSibling允许访问左节点和右节点.

例如:

代码名称

<!DOCTYPE HTML><html><head>   <title>My page</title></head><body>    <div>The header</div>     <ul><li>A list</li></ul>     <div>The footer</div></body> </body></html>
Copy after login

下图展示 (不包含空白标签):

浏览器总是保持正确的连接关系.

我们可能需要去改变DOM或者添加/移除元素, 但是不需要我们手动去改变他们, 浏览器来做这件事情.

总结

DOM 树是紧密相连的:

父辈

  • parentNode

子辈

  • children/childNodes ,  firstChild ,  lastChild

左右兄弟

  • previousSibling/nextSibling

浏览器保证所有连接关系都是正确的. 他们是只读权限. 如果没有一个元素(子节点, 父节点,相邻节点),他们的值都是null.

编程的人正在在线培训

"前端编程开发","后端开发","移动开发"等,

需要学习的可以加入群或者微信留言

原创内容,转载请注明出处.

公众微信号:bianchengderen

QQ群: 186659233

欢迎大家传播与分享.

融入编程人的生活,了解他们的思维模式,了解他们的喜怒哀乐,关注编程的人.

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative Overview HTML vs. CSS vs. JavaScript: A Comparative Overview Apr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Building the Structure of Web Pages HTML: Building the Structure of Web Pages Apr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

The Role of HTML: Structuring Web Content The Role of HTML: Structuring Web Content Apr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

See all articles