search
HomeWeb Front-endJS TutorialJavascript & DHTML Example Programming (Tutorial) DOM Basics and Basic API_Basic Knowledge

1. What is DOM?
What is DOM? DOM is the Document Object Model, which is a set of API interfaces based on browser programming (in this tutorial, it can be said to be DHTML programming). It is a recommended standard issued by the W3C. Each browser There are some subtle differences, among which Mozilla's browser is the closest to the standard. Simple Javascript needs to be combined with DOM to create beautiful effects and apply it to the WEB. This is almost the same as other languages. Just like C/C requires library support, otherwise it is just a matter of studying syntax. Therefore, you must have a certain understanding of DOM before you can apply Javascript to WEB or your RIA application, because DHTML In essence, it is to operate the DOM tree.
I hope you can bring the DHTML.chm manual with you in future programming. If you need to be compatible with gecko, I also want to bring the gecko DOM manual because there are too many APIs. If you don’t know the interface, you can also check this manual

If you want to test whether the browser supports DOM, you can judge with a simple sentence




2. DOM tree
Note: The root of the DOM tree is unified as the document root—document. Since the DOM is a tree structure, they naturally have the following relationships:

Root node (document)

Parent Node (parentNode)

Child Nodes (childNodes)

Brother Node Brother Node
(sibling) (sibling)

Example:

Suppose the HTML of the web page is as follows


never-online's website


tutorial of DHTML and javascript programming



We refer to the concept of tree and draw the DOM tree of the HTML document structure:

html

head

div title

text text

from above You can see from the icon that
html has Two child nodes, and html is the parent node of these two child nodes

Head has the node title, and there is a text node under the title

There is the node div under doby, and there is a text under the div Node

3. Manipulating the DOM tree
As mentioned at the beginning, the essence of DHTML is to manipulate the DOM tree. How to operate it? Suppose I want to change the text of the div node in the above HTML document, how to do it? [code]

never-online's website



<script> <BR>var isSupportDOM = !!document.getElementById; //两个取反,这已经在上节中说过了,意思是强制转型 <BR>alert("你的浏览器 " +(isSupportDOM?"":"不")+ "支持 DOM!"); <BR></script>tutorial of DHTML and javascript programming<script> <BR> function changedivText (strText) { <BR> var nodeRoot = document; //这个是根结点 <BR> var nodeHTML = nodeRoot.childNodes[0]; //这个是html结点 <BR> var nodeBody = nodeHTML.childNodes[1]; //body结点 <BR> var nodeDiv = nodeBody.childNodes[0]; //DIV结点 <BR> var nodeText = nodeDiv.childNodes[0];//文本结点' <BR> nodeText.data = strText; //文本节点有data这个属性,因此我们可以改变这个属性,也就成功的操作了DOM树中的一个结点了 <BR> } <BR> </script>
    
  


从上面的示例可以看出,我们可以用上面的这种方法操作DOM树上的任一节点。(注:1. 跨域除外,跨域通常是在操作frame上,简单的说,就是两个frame不属于同一域名。2.上面的操作为了演示,采用的方法是从根结点一直到文本结点的遍历,在DOM方法上,有更简洁的方法,这些以后会有更多示例加以说明,下文中也会有介绍)

三、DOM节点。
细心些的朋友也许发现了,在上面写的HTML代码时用与>包函起来的就是一个结点,事实上是这样的吗?答案是否定的。下面就是说说节点类型,否则在有的时候是会犯错误的。比如,你把上面的代码放到Mozilla firefox的浏览器里运行一下,就会知道了。
DOM中的结点类型比较多,这里写一些在HTML文档中(注:XML也是DOM树结构)常见的几种结点类型。

1、DOCUMENT_NODE
(document)文档根结点类型,该枚举型的值是9.

2、ELEMENT_NODE
(element)元素结点类型,该枚举型的值是1。上文中的html, body, div这些结点都是属于该类型。

3、TEXT_NODE
(text)文本结点类型,该枚举型的值是3。上文中的文本,如:tutorial of DHTML and javascript programming就是属于该类型。
(注:一个空格也就可能是一个文本结点)

通常更需要注意的是文本结点,有可能一个回车,一个空格都是文本结点。这一点以后会碰到,当然,我们也有办法处理,这里先不要急,以后也会说到的。

四、DOM常用的API

这些常用的API是要记下来的,当然在非IE的浏览器里也会有效,是符合w3c的。这些API在以后的编程中会常常用到。正如每个编程平台所提供的API一样,常用必须记下来,节省时间从而提高编程效率。只写几个最常用的,其它的API会在以后的示例中写出。由浅而深,从易到难嘛。

1、获取ELEMENT_NODE,元素节点
  1)、方法:document.getElementById(元素的Id),返回值为元素的节点引用。可以假想一下这个API的原理:象我们上面所做的是遍历每个节点(从根到我们所需结点),这个API,也可以想成是从根遍历,查询每个结点(空白结点和空结点除外),并获取该结点的id是否为指定的ID,如果是的话,就返回这个结点(注:在JS中,数组和对象是引用类型),如果没有就返回空。我们可以写写这个代码,帮助我们理解document.getElementById。下面是一个简单遍历BODY中元素的示例。


  
    never-online's website
    <script> <BR> function myGetElementById (id) { <BR> var nodeRoot = document; //这个是根结点 <BR> var nodeHTML = nodeRoot.childNodes[0]; //这个是html结点 <BR> var nodeBody = nodeHTML.childNodes[1]; //body结点 <BR> var bodyChild = nodeBody.childNodes; //body的孩子 <BR> for (var i=0; i<bodyChild.length; i++) { //简单的遍历(指body的孩子下的深度为1) <BR> if (bodyChild[i].id==id) return bodyChild[i]; <BR> }; <BR> return null; <BR> } <BR> function TestGetElementById (id) { <BR> var node = myGetElementById(id); <BR> if (node!=null) { <BR> alert("找到结点 "+id+"!"); <BR> alert(node.childNodes[0].data); <BR> } else { <BR> alert("没有找到结点 "+id+"."); <BR> } <BR> } <BR> </script>
  
  
    

    
tutorial of DHTML and javascript programming

    
  


  2)、属性:object.innerHTML,返回值:一个节点内的HTML值。该属性为可写属性。它虽然不是获取结点,但经常与获取结点相结合,所以我把它放在获取结点这一类,它的属性就类似于是纯文本节点属性中的data。以document.getElementById和object.innerHTML这两个API为例,我们就可以把上面所写的代码简化一下了,示例如下:


  
    never-online's website
    <script> <BR> function changedivText (strText) { <BR> var node = document.getElementById("textNode"); <BR> node.innerHTML = strText; <BR> } <BR> </script>
  
  
    
tutorial of DHTML and javascript programming

    
  


  3)、方法:object.getElementsByTagName(标签的名字),返回一个集合,该集合的把有元素都是有指定标签的元素。访问集合里的元素,可以用下标来访问。语法里的object,是指document(根)或者是一个ELEMENT_NODE。这个的原理示例我就不写了,可以作为一个作业,大家可以写写。这里写一些具体应用。如上例,我们还可以这样写。


  
    never-online's website
    <script> <BR> function changedivText (strText) { <BR> var node = document.getElementsByTagName("DIV"); <BR> node[0].innerHTML = strText; <BR> } <BR> </script>
  
  
    
tutorial of DHTML and javascript programming

    
  

再取一个例子,注意,BODY下的结点深度为2。


  
    never-online's website
    <script> <BR> function changedivText (strText) { <BR> var node = document.getElementById("nodeTest"); <BR> var myNode = node.getElementsByTagName("DIV"); <BR> myNode[0].innerHTML = strText; <BR> } <BR> </script>
  
  
    

      
tutorial of DHTML and javascript programming

      
    

  


二、动态创建与插入结点

  1)、创建结点对象。document.createElement(tagname),tagname指的是一个标签,比如一个DIV,就是document.createElement("DIV"),它返回的是这个结点的引用。

  2)、在body的尾部插入结点用document.body.appendChild(object),为了容易理解,下面这个示例,我用了IE专有的属性object.outerHTML,得到一个该元素的HTML标签内容(包括自身),这样会更容易看到效果。



  
    never-online's website
    <script> <BR> function insertNode (strText) { <BR> alert("插入元素前的body HTML: " +document.body.outerHTML); <BR> var node = document.createElement("DIV"); <BR> node.innerHTML = strText; <BR> document.body.appendChild(node); <BR> alert("插入元素后的body HTML: " +document.body.outerHTML); <BR> } <BR> </script>
  
  
    
tutorial of DHTML and javascript programming

    
  


  3)、在元素处插入结点。object.insertBefore(oNewNode [, oChildNode]),oNewNode为一个我们创建的结点,oChildNode是可选的,为object下的一个子节点。同样的,为了看到效果,我也用了outerHTML。示例


  
    never-online's website
    <script> <BR> function insertNode (strText) { <BR> alert("插入元素前的body HTML: " +document.body.outerHTML); <BR> var node = document.createElement("DIV"); <BR> var myNode = document.getElementById("textNode"); <BR> node.innerHTML = strText; <BR> document.body.insertBefore(node,myNode); <BR> alert("插入元素后的body HTML: " +document.body.outerHTML); <BR> } <BR> </script>
  
  
    
tutorial of DHTML and javascript programming

    
  


三、移除结点。
  1) object.parentNode.removeChild(oChildNode),这个就是语法,下面看示例。


  
    never-online's website
    <script> <BR> function insertNode (strText) { <BR> alert("插入元素前的body HTML: " +document.body.outerHTML); <BR> var node = document.createElement("DIV"); <BR> var myNode = document.getElementById("textNode"); <BR> node.innerHTML = strText; <BR> document.body.insertBefore(node,myNode); <BR> alert("插入元素后的body HTML: " +document.body.outerHTML); <BR> } <BR> function removeCreateNode() { <BR> alert("移除元素前的body HTML: " +document.body.outerHTML); <BR> var node = document.getElementById("textNode"); <BR> node.parentNode.removeChild(node); <BR> alert("移除元素前的body HTML: " +document.body.outerHTML); <BR> } <BR> </script>
  
  
    
tutorial of DHTML and javascript programming

    
    
  

这一节就先写到这里,下一节我们就可以用这几个简单的API做许多事情了,几个API就可以写出很多效果。:D 
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.