Home Web Front-end JS Tutorial JavaScript DOM Learning Chapter 1 Introduction to W3C DOM_Basic Knowledge

JavaScript DOM Learning Chapter 1 Introduction to W3C DOM_Basic Knowledge

May 16, 2016 pm 06:34 PM
dom javascript

In this chapter I mainly introduce the W3C first-level DOM that has been supported by the new generation of browsers. Gives you a general idea of ​​how they work and gives you an idea of ​​what you can do with them.
First, some suggestions for DOM and the purpose of DOM design, then I will tell you what nodes are and how to traverse nodes through the DOM tree. Next is how to get a specific node and how to change its values ​​and attributes. Finally, there is the ultimate goal of DOM: how to create a new node of your own.
Recommendation
Level 1DOM is developed by W3C to provide any programming language to access XML documents. No matter what language program you use to process XML documents, as long as it is the methods and attributes in Level 1DOM. Whether it's Perl, VBScript or JavaScript you can read any value you want and modify them.
As you may guess, this paragraph describes an ideal situation, and differences still exist (such as browsers). However, this part of the content is still relatively small, and learning how to process XML in JavaScript will also be helpful to your learning in other languages.
To some extent, HTML can also be regarded as an XML document. As long as the browser can handle the corresponding scripts, Level 1 DOM can also run very well in HTML.
You can read the text and attributes of each HTML tag, you can delete each tag and their content, and you can also insert a new tag into an existing document in real time without modifying it on the server. .
Because all aspects of modifying XML must be considered at the beginning of the design, there are some methods that may never be used by ordinary web engineers. For example, you can use it to modify HTML comments, but I don't see why you want to do this. There is also some DOM handling of DTD/Doctype content that you don't need in your web design, so ignore it and focus on your daily needs.
Nodes
The Document Object Model is a model of how multiple elements within a document are related to each other. In Level 1 DOM, every object is a node. So if you write:

Copy the code The code is as follows:

This is a paragraph


Then you create two nodes: the element P and the text node whose content is "This is a paragraph". This text node is contained within the P element, so it can be considered a child node of the p node. Conversely, the p element is the parent node of the text node.
If you write:
Copy the code The code is as follows:

This is a < ;B>Paragraph


Then the element node p has two child nodes, one of which has its own child node.
The last is the parameter node. (Confusingly, they don't count as children of element nodes. In fact, I did some testing while I was writing this chapter, and IE5 doesn't treat parameter nodes as children of elements at all.) So :
Copy code The code is as follows:

This is a paragraph



The structure of

may be like this:

       <P> ----------------<br><br>     --------------     ALIGN<br><br>  This is a     <B>     |<br>            |    right<br><br>          paragraph
Copy after login

This is the element node, text node and parameter node. 99% of HTML pages are composed of them, and your main task is how to place them. Of course, there are many other nodes, which will be skipped for now.

As you know, the p element also has its own parent node, which is usually the document, but sometimes it may be a DIV. So the entire document can be viewed as a tree composed of many nodes, and most of these nodes have their own child nodes.

      <BODY><br><br>        |-------------------------------------<br><br>       <P> ----------------      lots more nodes<br><br>     --------------     ALIGN<br><br>  This is a     <B>     |<br>            |    right<br><br>          paragraph
Copy after login

Traverse the DOM tree
Once you know the structure of the DOM tree, you can traverse it to find the elements you want. For example, assume that the element node p is already stored in the variable x (we will explain how this is done in a moment). If we want to access BODY at this time:
Copy code The code is as follows:
x.parentNode

We get the parent element of x, and then we can modify it. This way you can reach node B:
Copy code The code is as follows:
x.childNode[1]

childNode is an array containing all the child nodes of x. Of course, the array is numbered starting from 0, so childNode[0] is the text node "This is a " childNode[1] is the B node.
Two special ones: x.firstChild represents the first child node of x; x.lastChild represents the last child node of x.
Assume p is the first child node of BODY, and BODY is the first child node of document, so in order to reach node B, you can use any of the following methods:
Copy code The code is as follows:

document.firstChild.firstChild.lastChild;
document.firstChild.childNodes[0].lastChild;
document.firstChild.childNodes[0].childNodes[1];

Even this stupid one:
Copy code The code is as follows:
document.firstChild.childNodes[0].parentNode.firstChild.childNodes[1];

gets an element
However, Traversing the document this way is too cumbersome. Because the goal of Level 1 DOM design is to allow you to modify the entire DOM tree, you must accurately know the structure of the DOM tree, which will quickly lead to some problems.
So there are some ways to get to the element you want quickly. Once you get here, you can traverse every node of the entire DOM tree.
Let’s continue with the previous example. You want to reach element B. The easiest way is to just jump over. With document.getElementByTagName you can quickly create an array containing all B tags in the document. Assuming our B is the first one, then you can simply write:
Copy the code The code is as follows:
var x = document.getElementsByTagName('B')[0]

x contains element node B. First you instruct the browser to get all elements B(document.getElementByTagName('B')) of the entire document, and then you select the first element B([0]) of the first document, and you get what you want. .
You can also write:
Copy code The code is as follows:
var x = document.getElementsByTagName( 'P')[0].lastChild;

Now you first reach the first paragraph P of the document (assuming our P is the first element), and then reach the last child element of p.
The best way to reach the element accurately without requiring a DOM structure is to give B an ID:

This is a paragraph< ;/B>

Now you can simply write:
Copy the code The code is as follows:
var x = document.getElementById('hereweare');

Element B is stored in x.
Modify a Node
Now that we have reached the node, we can make some modifications. Suppose we want to change the bold bit of text to 'bold bit of text'. We need to access the correct element and modify its nodeValue. Now the correct element is not element B but its child element text node: what we want to change is the text, not the element. So you can write:
Copy code The code is as follows:
document.getElementById('hereweare').firstChild. nodeValue='bold bit of text';
The
element changes.
You can modify any text node or parameter through nodeValue. For example, you can modify the ALIGN parameter of a paragraph. This is also very simple, first find the element you need (in this case the parent element of the B element), and then use the setAttribute() method to set the value you want:
Copy code The code is as follows:
function test2(val) {
if (document.getElementById && document.createElement)
{
node = document.getElementById('hereweare').parentNode;
node.setAttribute('align',val);
}
else alert('Your browser doesn't support the Level 1 DOM');
}

创建和删除元素
修改元素固然有用,但是还是不如创建你需要的元素然后插入到现有的文档中。我可以很简单的在这个段落后面添加一个HR元素然后很简单的删除它。
创建元素使用下面的方法:
var x=document.createElemnt(‘HR')
这样HR就创建并且存储在x中。第二步就是把x插入到文档之中。我写了一个ID是inserthere的SPAN,我们就把它插入到这。所以我们使用appendChild()方法:
复制代码 代码如下:
document.getElementById('inserthrhere').appendChild(x);

删除它稍稍有点麻烦。我先创建一个临时变量node来存储SPAN,然后我告诉他移除他的第一个子元素:
复制代码 代码如下:

var node=document.getElementById(‘inserthere');
node.removeChild(node.childNode[0]);


同样的方法我们也可以创建一个新的元素然后添加在ID是hereweare的B元素上。
复制代码 代码如下:

var x = document.createTextNode(' A new text node has been appended!');
document.getElementById('hereweare').appendChild(x);

你可以试一试,你会注意到用老的办法可能不会移除新加的文本,那是因为他们已经成为分离的两部分了:
 <B><br><br> ------------<br><br> paragraph A new text node<br> has been appended!
Copy after login

(可以通过normalize()来把他们合并,但是IE5不支持)

我不打算告诉你怎么移除它,自己练习会比较有收获

翻译地址:http://www.quirksmode.org/dom/intro.html

转载请保留以下信息
作者:北玉(tw:@rehawk)
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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles