ProgramThe watershed between people (using back-end applications) and web programmers (writing HTML, CSS, and JavaScript) is long-lasting. However, the Document Object Model (DOM) makes up for this crack, making it practical to use hml at the front end while using XML at the back end, and becoming an extremely effective tool. In this article, Brett McLaughlin introduces the Document Object Model, explains its application in web pages, and starts to explore its usage in JavaScript.
Like many web programmers, you may have used HTML. HTML is the way programmers start to deal with Web pages. html is usually the last step before they finish the application or site-adjust some la S, colors, or styles. However, although HTML is often used, there are common misunderstandings about what happened when HTML is displayed on the screen in a browser. Before analyzing what you think may happen and the possible causes of errors, I want you to understand the process involved in designing and serving web pages:
- Some people (usually you !) Create HTML in a text editor or IDE.
- Then you upload HTML to a Web server, such as Apache httpd, and publish it on the internet or intranet.
- The user requests your web page using Firefox, Safaria, and other browsers.
- Your browser requests HTML from your server.
- The browser displays the page received from the server in graphics and text format. The user can view and activate the web page.
This seems very basic, but things will soon become interesting. In fact, a huge number of "stuff" occurs between step 4 and step 5, which is the focus of this article. The term "padding" is also very useful, because most programmers have never really considered what happened to the tag when the user's browser requests display the tag.
- Does the browser only read and display the text in HTML?
- What about CSS? Especially when CSS is in an external file.
- What about JavaScript? It is also usually located in an external file.
- How does the browser handle these items if it maps event handlers, functions, and styles to the text tag?
Practice has proved that all these questions are answered by the Document Object Model. Therefore, do not talk about Dom directly.
Web programmers and tags
For most programmers, their work ends when Web browsers start. That is to say, after you put an HTML file in the directory of a Web browser, you usually think that it has been completed, and (hopefully) think thatNever consider it again! This is also a great goal when it comes to writing clean and well-organized pages. We hope that you can mark cross-browser pages and display the content that should be displayed with various versions of CSS and JavaScript, no error at all.
The problem is that this method limits the programmer's understanding of what actually happens in the browser. More importantly, it limits your ability to dynamically update, modify, and reconstruct web pages with client JavaScript. With this restriction, your web site can be more interactive and creative.
What do programmers do
As a typical web programmer, you may start text editing and IDE before entering HTML, CSS, and even JavaScript. It is easy to think that these tags, selectors, and attributes are just small tasks that make the site correctly displayed. However, you need to expand your thinking and realize that you are organizing your content. Don't worry; I promise this won't turn into a lecture on how to mark the appearance, how you must recognize the real potential of web pages, or any other metamaterial. You need to know what role you are playing in Web development.
When it comes to the page appearance, you can only provide suggestions. When you provide a CSS style sheet, you can overwrite your style selection. You provide a font size that your browser can change for the blind or scale down proportionally on a large display (with the same resolution. Even the color and font you select are subject to the user's display and font installed on the user's system. Although it is good to do your best to design the page styleNeverYou have the greatest impact on Web pages.
What you absolutely control is the Web PageStructure. Your mark cannot be changed, and the user cannot be confused; their browsers can only retrieve tags from your web server and display them (although the style is more in line with user taste than your own taste ). However, the page organization, whether in this section or in other partitions, is only determined by you. If you want to actually change your page (which is the focus of most Ajax applications), you operate on the page structure. Although it is easy to change the color of a piece of text, it is much harder to add text or the entire section on an existing page. No matter how you design the style of the section, you control the organization of the page itself.
Mark what to do
Once you realize that your tag is really related to the organization, you will see it differently. Not ConsideredH1As a result, the text is large, black, and boldH1Is the title. What do users think about this problem and whether they use your CSS, their own CSS, or the combination of the two are secondary considerations. On the contrary, you must realize that only tags can provide organizations of this level;PSpecifies that the text is in the paragraph,IMGIndicates the image,DivDivide the page into segments.
It should also be clear that the style and behavior (event handler and JavaScript) are inEx postApplied to the Organization. You can only operate on or design a style after you mark it as ready. Therefore, just as you can save CSS in an HTML external file, the tag organization is separated from its style, format, and behavior. Although you can certainly use JavaScript to change the element or text style, it is more interesting to actually change the organization of your tag.
As long as you keep in mind that your tag only provides organization and framework for your page, you will be undefeated. One small step further, you will understand how the browser accepts all the text organizations and converts them into something super interesting, that is, a group of objects, each object can be changed, added, or deleted.
|
Other ideas about tagging Edit plain text: Right? Text is ideal for storing tags, but not suitableEditMark. IDE, such as Macromedia Dreamweaver or Microsoft FrontPage, is widely used to operate web page tags. These environments usually provide shortcuts and help to create web pages, especially when CSS and JavaScript are used, they both come from files other than the actual page tag. Many people still prefer to use old notebooks or VI (I admit I am one of them), which doesn't matter. In any case, the final result is a text file filled with markup. Text on the Network: good stuff As we have already said, text is the best media for a document, such as HTML or CSS, which is transmitted over the Internet thousands of times. When I say that it is difficult for a browser to express text, it refers to converting text into a visual image page that users can view. This has nothing to do with how the browser actually retrieves pages from the web browser; in this case, text is still the best choice. |
|
Advantages of text tagging
Before discussing Web browsers, it is worth considering why plain textAbsoluteIs the best choice for storing HTML (for more information, see some other ideas about tag ). Without considering the advantages and disadvantages, I just recall that HTML is sent to the Web browser through the network every time I view the page (for simplicity, I do not consider high-speed caching, etc ). There are no more effective methods than passing texts. Binary objects, graphic representation of pages, re-organized tag blocks, and so on, all of which are more difficult than passing plain text files over the network.
In addition, the browser also adds luster. Today's Browser allows users to change text size, scale images proportionally, download CSS or JavaScript on pages (in most cases), or even more, this completely eliminates the need to send any type of page graphical representation to the browser. However, the browser needs the original HTML so that it can apply any processing to the page in the browser, rather than trusting the browser to process the task. Similarly, separating CSS from JavaScript and separating CSS from HTML tags requires a format that is easy to separate. Text Files once again become the best method for this task.
Last but equally important, remember that the new standard (such as HTML 4.01 and XHTML 1.0 and 1.1) promises to include content (data in the page) and representation and style (usually applied by CSS) separated. If the programmer wants to separate HTML from CSS and then forces the browser to search for some page representations of each part of the bonded page, this will lose most of the advantages of these standards. Keeping these parts separated when they arrive at the browser gives the browser unprecedented flexibility in getting HTML from the server.
Learn more about Web browsers
For some web programmers, all the content read above may be a funny story about your role during web development. But when it comes to browser behavior, many of the most competent web designers and developers are usually not aware of the "Inside" situation. I will focus on this section. Don't worry,CodeIt's coming soon, but you have to restrain your code from impatience, because it's critical to really understand the exact behavior of Web browsers for your code to work correctly.
Disadvantages of text tagging
Just as text markup has amazing advantages for designers and page creators, it also has surprising disadvantages for browsers. Specifically, it is difficult for a browser to directly present text tags to users visually (for more information, see some other ideas about tagging ). Consider the following common browser tasks:
- Apply CSS styles (usually from multiple style sheets in external files) to tags Based on element types, classes, IDs, and their locations in HTML documents.
- Apply styles and formats to different parts of HTML documents based on JavaScript code (usually in external files.
- Modify the value of a form field based on JavaScript code.
- Based on JavaScript code, it supports visual effects, such as image flip and image exchange.
The complexity is not about coding these tasks; everything is quite easy. Complexity comes from browsers that actually implement request actions. If the tag is stored as text, for example, you wantCenter-TextClassPInput text in the element (Text-align: Center), How to implement it?
- Add inline styles to text?
- Apply the style to HTML text in the browser and keep the content centered or not centered?
- Apply the HTML without a style, and then apply the format afterwards?
These very difficult problems are the cause of few browsers today. (The person who wrote the browser should accept the most sincere thanks)
Without a doubt, plain text is not a good way to store browser HTML, although text is the best solution for getting page tags. If Javascript is addedChangeThe page structure becomes more subtle. Should the browser rewrite the modified structure to the disk? How can we maintain the latest version of the document?
No doubt, text is not the answer. It is difficult to modify, and it is very difficult to apply styles and behaviors for it. It is fundamentally different from the dynamic nature of today's web pages.
Turn to Tree View
The answer to this question (at least the answer selected by today's Web browsers) is to use a tree structure to represent HTML. See Listing 1. This is a simple and boring HTML page.
Listing 1. simple HTML page in text tag
<html>
<head>
<title>Trees, trees, everywhere</title>
</head>
<body>
<h1>Trees, trees, everywhere</h1>
<p>Welcome to a <em>really</em> boring page.</p>
<div>
Come again soon.
<img src="come-again.gif" />
</div>
</body>
</html> |
|
The browser accepts the page and converts it to a tree structure, as shown in 1.
Figure 1. Tree View in Listing 1
To keep the progress of this article, I have simplified it a little. Dom or XML experts will be aware of the impact of blank spaces on the representation and decomposition of document text in the Web browser tree structure. Superficial Understanding can only make things ambiguous, so if you want to figure out the influence of the blank, you 'd better not think about it. If you don't want to, you can continue to read it. When it becomes a problem, you will understand everything you need.
In addition to the actual tree background, you may first notice that everything in the tree contains elements in the outermost HTML, that isHtmlElement. The tree metaphor is calledRoot element. So even if this is the bottom layer of the tree, When you view and analyze the tree, I usually start with this. If it does, you can turn the entire tree upside down, but it does extend the tree metaphor.
The line from the root represents the relationship between different marked parts.HeadAndBodyElement isHtmlRoot elementChild;TitleYesHeadWhile the text "trees, trees, everywhere" isTitle. The entire tree is organized in this way until the browser obtains a structure similar to figure 1.
Additional Terms
To use the tree metaphor,HeadAndBodyCalledHtmlOfBranches). They are called branches because they have their own children. When you reach the end of the tree, you will enter the main text, such as "trees, trees, everywhere" and "really ".LeafBecause they do not have their own children. You don't need to remember all these terms. When you try to figure out the meaning of a specific term, it's much easier to think about the tree structure.
Object Value
Now that you understand some basic terms, you should take a look at the small rectangle containing the element name and text (figure 1 ). Each rectangle is an object. The browser solves some text problems. By using objects to represent each part of an HTML document, you can easily change the organization, apply the style, and allow JavaScript to access the document.
Object Type and attribute
Each possible type of the tag has its own object type. For exampleElementObject type. Text in the documentTextType.AttributeType, and so on.
Therefore, Web browsers can not only use object models to represent documents (thus avoiding static text processing), but also use object types to immediately identify what a thing is. The HTML document is parsed and converted to an object set, as shown in Figure 1. Then, angle brackets and escape sequences (for example, use<Indicates<, Use>Indicates>. This makes it easier for the browser to work (at least after parsing the input html. It is easy to find out whether a thing is an element or an attribute and determine how to process the type of object.
By using objects, Web browsers can modify the attributes of these objects. For example, each element object has a parent element and a series of child elements. Therefore, to add a new child element or text, you only need to add a new child element to the child element list of the element. These objects also haveStyleSo it is very easy to quickly change the style of an element or text segment. For example, to use JavaScript to changeDivIs as follows:
Somediv. style. Height = "300px "; |
In other words, Web browsers can easily change the tree's appearance and structure by using object properties. It is similar to the complex things that must be performed when the browser internally expresses the page as text. Every time you change the attribute or structure, the browser needs to re-compile the static file, re-parse the file, and re-display it on the screen. With the object, all this is done.
Now, take some time to expand some HTML documents and sketch them out in a tree. Although this looks like an unusual request (especially in such an article that contains very little code)ArticleIf you want to manipulate these trees, you need to be familiar with their structures.
In this process, you may find some strange things. For example, consider the following situations:
- What happened to the property?
- Decomposed into elements (suchEmAndB) Text?
- Incorrect structure (for example, when the end is missingPWhat about html?
Once you are familiar with these problems, you can better understand the following sections.
Strict and sometimes good
If you try exercise I, you may find some potential problems in the marked Tree View (if you do not want to practice it, let me know !). In fact, some problems are found in Listing 1 and figure 1.PHow elements are decomposed. If you ask a common web developer"PWhat is the text content of an element? The most common answer is "Welcome to a really boring web page .". If you compare it with figure 1, you will find that this answer (although logical) is fundamentally incorrect.
Actually,PElement hasThreeDifferent sub-objects, none of which contain the complete "Welcome to a really boring web page." text. You will find part of the text, such as "Welcome to a" and "Boring Web page", but not all. To understand this, remember that everything in the tag must be converted to a certain type of object.
In addition, the order is irrelevant! If the browser displays the correct object, but the display order is different from the order you provided in HTML, how can you imagine the user responding to the Web browser? The Section is in the middle of the page title and article title, and this is not the style when you organize the document yourself? Obviously, the browser must keep the order of elements and text.
In this example,PThe element has three different parts:
- EmText before the element
- EmElement itself
- EmText after Element
If this order is disrupted, the emphasis may be placed on the text error section. To keep everything normal,PThe element has three child objects in the order displayed in the HTML of Listing 1. In addition, the key text "really"No PButPChild ElementEm.
Understanding this concept is very important. Although the "really" text may be associated with otherPThe element text is displayed together, but it is stillEmThe direct child element of the element. It can havePDifferent text formats, and can be moved everywhere independently of other texts.
Keep this in mind and try to use graphs to represent the HTML in Listing 2 and 3 to ensure that the text has the correct parent element (regardless of how the text will eventually be displayed on the screen ).
Listing 2. tags with cleverly nested Elements
<html>
<head>
<title>This is a little tricky</title>
</head>
<body>
<h1>Pay <u>close</u> attention, OK?</h1>
<div>
<p>This p really isn't <em>necessary</em>, but it makes the
<span id="bold-text">structure <i>and</i> the organization</span>
of the page easier to keep up with.</p>
</div>
</body>
</html>
|
Listing 3. More clever element nesting
<html>
<head>
<title>Trickier nesting, still</title>
</head>
<body>
<div id="main-body">
<div id="contents">
<table>
<tr><th>Steps</th><th>Process</th></tr>
<tr><td>1</td><td>Figure out the <em>root element</em>.</td></tr>
<tr><td>2</td><td>Deal with the <span id="code">head</span> first,
as it's usually easy.</td></tr>
<tr><td>3</td><td>Work through the <span id="code">body</span>.
Just <em>take your time</em>.</td></tr>
</table>
</div>
<div id="closing">
This link is <em>not</em> active, but if it were, the answers
to this <a href="answers.html"><img src="exercise.gif" /></a> would
be there. But <em>do the exercise anyway!</em>
</div>
</div>
</body>
</html>
|
The answers to these exercises will be found in the tricky-solution.gif in Figure 2 at the end of this article, GIF files, and the trickier-solution.gif in figure 3. Don't peek. Take some time to answer questions automatically. This helps you understand how strict the rules are applied in the organization tree, and truly help you grasp the HTML and its tree structure.
What about attributes?
When you try to figure out how to handle attributes, do you have any problems? As mentioned above, an attribute does have its own object type, but it is not a child element of its element. The nested element and text are not in the same attribute "level". You will notice that, the answers to exercises in Listing 2 and 3 do not show attributes.
Attributes are actually stored in the object model used by the browser, but they have some special situations. Each element has a list of available attributes separated from the list of sub-objects. SoDivAn element may have a list containing the attribute "ID" and another attribute "class.
Remember, the attribute of an element must have a unique name. That is to say, an element cannot have two "IDS" or two "class" attributes. This makes the list easy to maintain and access. As you can see in the next article, you can callGetattribute ("ID ")To obtain the attribute value by name. You can also call it in a similar way to add a property or set (reset) the value of an existing property.
It is worth noting that the uniqueness of attribute names makes the list different from the sub-Object List.PThe element can have multipleEmThe sub-Object List can contain multiple repeated items. Although the subitem list and attribute list are operated in a similar way, one can contain duplicate items (the subitem of an object), and the other cannot (the attribute of an element object ). Finally, only elements have attributes, So text objects do not have an additional list for storing attributes.
Messy html
Before proceeding, we will talk about how the browser converts tags into tree representations. Another topic worth exploring is how the browser handles poorly formatted tags.Good formatIt is a widely used term in XML and has two basic meanings:
- Each start tag has a matched end tag. So each<P>In the document</P>Match, each<Div>And</Div>Match, and so on.
- The Start mark in the innermost part matches the end mark in the innermost part, and the Start mark in the second matches the end mark in the second, and so on. So<B> <I> bold and italics </B> </I>It is invalid because the Start mark in the innermost part<I>And the ending mark in the innermost part<B>Improper matching. To make it in good format,OrSwitch start to mark the order,OrSwitch end tag order. (If both are switched, problems still occur ).
Study these two rules in depth. These two rules not only simplify the document organization, but also eliminate uncertainty. Should bold text be applied first and then italic text be applied? Or exactly the opposite? If you think this order and uncertainty are not a big problem, remember that CSS allows rules to overwrite other rules.BThe text font in the element is different fromIThe font in the element, the application order of the format will become very important. Therefore, the good HTML format plays an important role.
If the browser receives a document that is not in good format, it will do its best. In the best case, the resulting tree structure will be the approximate structure of the original page that the author wants. In the worst case, it will be completely invisible. If you have loaded the page into the browser and see a completely unexpected result, you may wonder how your structure should be and continue working with frustration when you see the browser result. Of course, it is quite simple to solve this problem: Make sure that the document is in good format! If you are not clear about how to compile standard HTML, please consult references for help.
Introduction to Dom
So far, you know that the browser converts a web page to an object representation. You may even guess that the object representation is a DOM tree. Dom indicates the Document Object Model, which is a standard and can be obtained from the World Wide Web Consortium (W3C) (see some Dom-related links in references ).
But more importantly, Dom defines the object type and attributes, allowing the browser to indicate the tag. (The next article in this series will detail how to use DOM in JavaScript and Ajax code .)
Document Object
First, you need to access the object model itself. This is very easy; use built-in in any JavaScript code running on the web pageDocumentVariable, you can write the following code:
Of course, this code is useless, but it demonstrates that every web browser makesDocumentThe object can be used in JavaScript code and demonstrates the complete tree of the object that represents the mark (figure 1 ).
Each item is a node
Apparently,DocumentObjects are very important, but this is just the beginning. Before further exploration, you need to learn another term:Node. You already know that each part of the tag is represented by an object, but it is not just an arbitrary object, it is a specific type of object, a DOM node. More specific types, such as text, elements, and attributes, all inherit from this basic node type. Therefore, there can be text nodes, element nodes, and attribute nodes.
If you already have a lot of JavaScript programming experience, you may already be using Dom code. If you have been tracking this Ajax series so farYesDom code has been used for some time. For example, the code lineVaR number = Document. getelementbyid ("phone"). value;Use the Dom to search for a specific element and then retrieve the value of the element (in this example, it is a form field ). So even if you are not aware of thisDocumentDom is used when you type JavaScript code.
To explain in detail the terms that have been learned, the DOM tree is the object tree, but more specifically, it isNodeObject Tree. In Ajax applications or any other JavaScript, these nodes can be used to produce the following effects, such as removing elements and their content, highlighting specific text, or adding new image elements. Because it occurs on the client (the code running in the Web browser), these effects happen immediately without communicating with the server. The final result is usually that the application feels faster, because content changes on the Web page do not pause for a long time when the request is redirected to the server and the response is interpreted.
In the majorityProgramming Language, You need to learn the actual object name of each node type, learn available attributes, and find out the type and forced conversion; but this is not necessary in JavaScript. You can create only one variable and assign it the object you want (as you can see ):
var domTree = document;
var phoneNumberElement = document.getElementById("phone");
var phoneNumber = phoneNumberElement.value;
|
No type. Javascript creates variables as needed and assigns them the correct type. As a result, the use of DOM in Javascript becomes insignificant (in the future there will be an article dedicated to the DOM related to XML, which will be more clever at that time ).
Conclusion
Here, I want to give you some suspense. Obviously, this is not a fully detailed description of Dom; in fact, this article is just an introduction to Dom. Dom has much more content than I have introduced today!
The next article in this series will expand these ideas and explore how to use DOM in JavaScript to update web pages, quickly change HTML, and create a more interactive experience for your users. In the subsequent articles devoted to using XML in Ajax requests, I will return to discuss Dom again. So be familiar with Dom, which is a major part of Ajax applications.
At this point, it will be very easy to understand the Dom, for example, how to move in the DOM tree, get the value of elements and text, traverse the node list, and so on, but this may give you the impression that Dom is about code, but not actually.
Before reading the next article, try to think about the tree structure and use some of your own HTML practices to see how the web browser converts HTML into a marked tree view. In addition, let's take a look at the DOM tree organization and use the special cases introduced in this article to practice: the text of the attribute and element in it,NoElements of text content (for exampleIMGElement ).
If you have mastered these concepts and then learned the JavaScript and Dom syntax (next article), it will make the response easier.
And don't forget, here are the answers in Listing 2 and 3, which also contain the sample code!
Figure 2. Answer in Listing 2
Figure 3. Answer in listing 3
References
Learning
-
- For more information, see the original article on the developerworks global site.
-
- Learn how to introduce ajax to the first several articles in this developerworks series:
- "Understanding Ajax, Part 1: Ajax Introduction" Part 2 demonstrates how Ajax component technology works together and exposes the core concepts of Ajax, includingXMLHttpRequestObject (January 2006 ).
- "Understanding Ajax, Part 1: using JavaScript and Ajax to send asynchronous requests" Part 2 shows how to create a cross-browserXMLHttpRequestInstance, construct and send requests, and respond to the server (January 1, February 2006 ).
- "Grasp Ajax, Part 1: Advanced requests and responses in Ajax" Part 2 demonstrates how to execute standard web forms in Ajax and how to master the HTTP status code, readiness, andXMLHttpRequestObject understanding (January 1, March 2006 ).
-
- Dom homepage on the World Wide Web Alliance: entry to all Dom-related content.
-
- Dom Level 3 Core Specification: defines the Core Document Object Model, covering available types and attributes and Dom usage in various languages.
-
- Ecmascript language Bindings for DOM: if you are a javascript programmer and want to use DOM in code, this appendix defined by Level 3 Document Object Model core will be recommended to you.
-
- "Ajax for Java developers: building dynamic Java applications": This article observes server-side Ajax from the Java perspective, introduced a breakthrough method for creating dynamic web application experiences (developerworks, September 2005 ).
-
- "Java object serialization for Ajax: Ajax for Java developers": describes five methods for Java object serialization, I also discussed how to send objects over the network and how to interact with Ajax (developerworks, November October 2005 ).
-
- "Using ajax to call soap Web Services, Part 1: Building Web service clients": this fairly advanced article discusses in depth how to integrate Ajax with existing soap-based Web Services; demonstrate how to use the Ajax design pattern to implement a web browser-based soap web service client (developerworks, October 2005 ).
-
- "Ajax: A New Approach to Web Applications": This document creates the Ajax name, which is a must-read task by all Ajax developers.
-
- HTTP status code: view the complete list of status codes from W3C.
-
- Head rush AjaxAuthor elisw.freeman, Eric Freeman, and Brett McLaughlin (February 2006, o'reilly media, Inc.): puts the concept of this article into your brain in a simple way.
-
- Java and XML, Version 2, author Brett McLaughlin (August 2001, o'reilly media, Inc.): Read the author's discussion of XHTML and XML Conversion.
-
- Javascript: the definitive guideBy David Flanagan (November 2001, o'reilly media, Inc.): provides a comprehensive description of using JavaScript and dynamic web pages. In future versions, we will add two chapters on Ajax.
-
- Head first HTML with CSS & XHTMLElizabeth and Eric Freeman (o'reilly media, inc., December 2006): Read the complete code, learn XHTML, CSS, and how to use them together.
-
- Developerworks Web architecture area: Expand your web build capabilities.
-
- Developerworks technical events and webcasts: Provides technical developers with the latest text about these software.
Obtain products and technologies
- IBM trial software: Build your next development project with software that can be downloaded directly from developerworks.
Discussion
- Developerworks blog: Join developerworksCommunity.
About the author
|
|
|
Brett McLaughlin has been using computers since the logo age. (Remember the triangle ?) In recent years, he has become one of the most famous authors and programmers in the Java and XML communities. He has implemented complex enterprise systems at Nextel communications, written application servers at lutris technologies, and recently continued to write and edit books in o'reilly media, Inc. Brett's upcoming new bookHead rush Ajax, Along with the best-selling author Eric and Beth Freeman, the award-winning revolutionary head first method for Ajax. Recent worksJava 1.5 Tiger: A developer's notebookIs the first book about the latest Java technology version, classicJava and XMLIt is still an authoritative book using XML technology in Java. |