[Four days learn Ajax] Learn Ajax tutorials fourth day, using DOM for WEB response

Source: Internet
Author: User
Tags add format object end html page object model variable access
Ajax|dom|web| Tutorials | In the case of an external file in HTML, the organization of the tag is separated from its style, format, and behavior. Although you can certainly change the style of elements or text with JavaScript, it is more interesting to actually change the organization that your markup is assigned to.

Just keep in mind that your tags only provide an organization and framework for your pages, and you will be invincible. One small step, you will understand how browsers accept all text organizations and turn them into something super interesting-a set of objects in which each object can be changed, added, or deleted.

Advantages of text Markers

Before discussing a Web browser, it's worth considering why plain text is absolutely the best choice for storing HTML (see some other ideas about tags for more information). Regardless of the pros and cons, just recall that HTML is sent over the network to the Web browser each time you view the page (for simplicity, regardless of caching, etc.). There is no more effective way to pass text. Binary objects, graphic representations of the page, the block of tags that are organized, and so on, all of which are more difficult to pass through the network than plain text files.

In addition, the browser also adds luster to this. Today's browsers allow users to change the size of text, scale images, download pages of CSS or JavaScript (most of the same), or more, which completely excludes the sending of any type of page graphic 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 handle the task. Similarly, separating CSS from JavaScript and separating CSS from HTML tags requires an easy to detach format. The text file is once again the best way to do this task.

Last but not least, remember that the new standards (such as HTML 4.01 and XHTML 1.0 and 1.1) are committed to separating the content (the data in the page) from the presentation and style (which is usually applied by CSS). If the programmer wants to detach HTML from the CSS, and then force the browser to retrieve pages that are part of the cohesive page, this will lose most of the benefits of these standards. Keeping these parts out of the browser leaves the browser with unprecedented flexibility in getting HTML from the server.

Other ideas about the tag

Plain text edit: Is it right or wrong?
Plain text is the ideal choice for storing tags, but not for editing tags. The main way to do this is to use the IDE, such as Macromedia DreamWeaver or a more powerful microsoft®frontpage®, to manipulate Web page markup. These environments often provide shortcuts and help to create Web pages, especially when using CSS and JavaScript, both from files outside of the actual page markup. Many people still love to use the old Notepad or VI (I admit I am also one of them), it does not matter. In any case, the end result is a text file full of markup.

Text on the network: Good Things

As has been said, text is the best medium for a document, such as HTML or CSS, which is transmitted over the web thousands of thousand. When I say that the browser is difficult to represent text, it refers specifically to converting the text into a visual graphic page that the user views. This is not related to how the browser actually retrieves pages from a Web browser, in which case the text is still the best choice.

Disadvantages of text Markers

Just as text tags have amazing advantages for designers and page creators, it is also surprisingly flawed for browsers. Specifically, it is difficult for browsers to visually represent text tags directly to users (see some other ideas about tags for more information). Consider the following common browser tasks:

• Apply CSS styles (usually from multiple style sheets in external files) to tags based on the element type, class, ID, and its location in the HTML document.
• Apply styles and formatting to different parts of an HTML document based on JavaScript code (usually in an external file).
• Change the value of a form field based on JavaScript code.
• Supports visual effects, such as image rollover and image swapping, based on JavaScript code.

Complexity is not about coding these tasks; everything is fairly easy. Complexity comes from the browser that actually implements the request action. If the tag is stored as text, for example, to enter text (Text-align:center) in the P element of the Center-text class, how do you implement it?

• Add inline styles to text?
• Apply styles to HTML text in the browser and keep content centered or not centered?
• Apply unformatted HTML and then apply formatting afterwards?

These very difficult questions are why few people write browsers today. (People who write browsers should accept the most heartfelt thanks)

No doubt, plain text is not a good way to store browser HTML, although text is the best solution for getting page tags. If you add JavaScript to the ability to change the page structure, things get a little tricky. Should the browser write the modified structure back to disk? How do you keep the latest version of your document?

No doubt, the text is not the answer. It's hard to modify, and it's difficult to apply styles and behavior, fundamentally far from the dynamic nature of today's Web pages.

Turn to tree view

The answer to this question, or at least the answer chosen by today's Web browser, is to use the tree structure to represent HTML. See Listing 1, which is a fairly simple and boring HTML page represented by this article.

Listing 1. A simple HTML page in a text tag

<title>trees, Trees, everywhere</title>
<body>
<p>welcome to a <em>really</em> boring page.</p>
<div>
Come again soon.

</div>
</body>

The browser accepts the page and converts it to a tree structure, as shown in Figure 1.

To keep the progress of this article, I made a little simplification. Experts in the DOM or XML are aware of the effects of whitespace on how document text is represented and decomposed in a Web browser tree structure. Superficial understanding can only make things ambiguous, so if you want to understand the impact of the blank, it is best, if you do not want to, then read on, do not consider it. When it becomes a problem, then you will understand everything you need.

In addition to the actual tree background, it is possible to first notice that everything in the tree begins with the outermost HTML containing element, the HTML element. Using the metaphor of the tree, this is called the root element. So even if this is the bottom of the tree, when you look at and analyze the tree, I usually start with that. If it does work, you can turn the whole tree upside down, but it does extend the metaphor of the tree.

Lines that flow from the root represent the relationships between the different tag parts. Head and body elements are children of HTML root elements; title is the child of head, and the text "trees, trees, everywhere" is the child of title. The entire tree is organized in this way until the browser obtains a structure similar to Figure 1.

Some additional terms

To follow the metaphor of the tree, head and body are called the branches of HTML (branches). They're called branches because they have children of their own. When you reach the end of the tree, you will enter the main text, such as "trees, trees, everywhere" and "really"; these are often called leaves because they have no children of their own. You don't have to memorize all these terms, and when you try to figure out what a particular term means, it's much easier to imagine the tree structure.

The value of the object

Now that you know some basic terminology, you should focus on the small rectangles that contain the element names and text (Figure 1). Each rectangle is an object, in which the browser resolves some text problems. By using objects to represent each part of an HTML document, you can easily change your organization, apply styles, allow JavaScript to access documents, and so on.

Object Types and properties

Each possible type of markup has its own object type. For example, elements in HTML are represented by element object types. The text in the document is represented by a text type, which is represented by an attribute type, and so on.

So Web browsers can not only use the object model to represent the document (thereby avoiding the processing of static text), but can also use object types to immediately identify what something is. The HTML document is parsed and converted to a collection of objects, as shown in Figure 1, and then the angle brackets and escape sequences (for example, using < notation, using > to express >) are no longer a problem. This makes it easier for the browser to work (at least after parsing the input HTML). It's easy to figure out whether something is an element or an attribute and determine how to handle the object of that type.

By using objects, WEB browsers can change the properties of these objects. For example, each element object has a parent element and a series of child elements. So adding a new child element or text simply adds a new child element to the element's list of child elements. These objects also have a style attribute, so it is easy to quickly change the style of an element or text segment. For example, to use JavaScript to change the height of a div, as follows:

SomeDiv.style.height = "300px";

In other words, a Web browser uses object properties to make it very easy to change the look and structure of a tree. Compare it to the complex things that a browser has to do to represent a page internally as text, and each time you change a property or structure, you need the browser to rewrite the static file, reparse it, and then display it again on the screen. With the object, all this was settled.

Now, take the time to expand some HTML documents and sketch them out with the tree. Although this may seem like an unusual request (especially in an article with minimal code), if you want to be able to manipulate the trees, you need to be familiar with their structure.

In the process, you may find some strange things. For example, consider the following:

• What happened to the attribute?
• Text that is decomposed into elements (such as EM and b)?
• Is the HTML of the structure not correct (for example, when the end P tag is missing)?

Once you are familiar with these questions, you will have a better understanding of the following sections.

Strictly sometimes it's good.

If you try the exercise I just mentioned, you may find some potential problems in the Tagged tree view (if you don't practice, listen to me!) )。 In fact, in Listing 1 and Figure 1, you'll find some problems, first of all, to see how the P element is decomposed. If you ask the typical web developer what the text content of the P element is, the most common answer would be "Welcome to a really boring Web page." If you compare it to Figure 1, you will find that the answer (although logical) is simply not correct.

In fact, the P element has three different child objects, none of which contains 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 any content in the tag must be converted to a type of object.

In addition, the order is irrelevant! If the browser displays the correct objects, but the order of display is different from the order that you provide in HTML, can you imagine how the user will respond to a Web browser? Is the paragraph in the middle of the page title and the title of the article, and isn't that what you did when you organized your document? Obviously, the browser must keep the elements and the order of the text.

In this case, the P element has three different parts:

Text before the EM element
EM element itself
Text after the EM element

If you upset the order, you might focus on the wrong part of the text. To keep everything normal, the P element has three child objects in the order that they appear in the HTML of Listing 1. Moreover, the emphasis text "really" is not a child element of P, but a child element of P's child element em.

It is very important to understand this concept. Although the "really" text may appear along with other p-element text, it is still a direct child of the EM element. It can have a different format than the other P text and can be moved around independently of other text.

To keep this in mind, try to figure out the HTML in listings 2 and 3 to make sure that the text has the correct parent element (regardless of how the text will eventually appear on the screen).

Listing 2. tags with ingenious element nesting

<title>this is a little tricky</title>
<body>
<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>

Listing 3. More subtle nesting of elements

<title>trickier Nesting, still</title>
<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>
As it ' s usually easy.</td></tr>
<tr><td>3</td><td>work through the <span id= "code" &GT;BODY&LT;/SPAN&GT;.
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" ></a>
Be there. But <em>do the exercise anyway!</em>
</div>
</div>
</body>

The answers to these exercises will be found in the tricky-solution.gif in Figure 2 of the GIF file in the end of this article and in Trickier-solution.gif in Figure 3. Do not peek, take some time to automatically answer. This helps you understand how strict the rules applied when organizing trees, and really helps you master HTML and its tree structure.

What about the attributes?

When you try to figure out how to handle a property, do you encounter some problems? As mentioned before, a property does have its own object type, but the property is not a child of the element that is displaying it, and the nested elements and text are not at the same property level, and you will notice that the answers to the exercises in listings 2 and 3 do not display attributes.

Properties are actually stored in the object model that the browser uses, but they have some special circumstances. Each element has a list of available attributes, and is separate from the list of child objects. So the DIV element might have a list that contains the attribute "id" and another attribute "class".

Remember that the attributes of an element must have a unique name, that is, an element cannot have two "id" or two "class" attributes. This makes the list easy to maintain and access. As you'll see in the next article, you can simply call a method such as getattribute ("id") to get the value of the property by name. You can also use a similar method to add a property or set (reset) The value of an existing property.

It is worth noting that the uniqueness of the property name makes the list different from the list of child objects. P elements can have multiple EM elements, so a list of child objects can contain multiple duplicates. Although the list of subkeys and property lists operate similarly, one can contain duplicates (the children of an object), and one cannot (the attributes of an element object). Finally, only elements have attributes, so the text object does not have an additional list for storing properties.

Messy HTML

Before continuing, when it comes to how browsers convert markup to tree representations, there is another topic worth exploring: How browsers handle not well-formed tags. Good format is a term that is widely used in XML, with two basic meanings:

• Each start tag has a closing tag that matches it. So each <p> in the document matches with </p>, each <div> and </div> match, and so on.
• The innermost start tag matches the innermost end tag, and then the start tag in the second matches the closing tag inside the secondary, and so on. So <b><i>bold and italics</b></i> are illegal because the innermost start tag <i> the innermost end tag <b> match improperly. To make it well-formed, either toggle the start tag order or toggle the end tag order. (problems will still occur if both are switched.)
Study these two rules in depth. These two rules not only simplify the organization of the document, but also eliminate the uncertainty. Should italic be applied before bold is applied? Or the opposite? If you find this order and uncertainty not a big problem, keep in mind that CSS allows rules to override other rules, so, for example, if the text in the B element differs from the font in the I element, the order in which the formatting is applied becomes very important. Therefore, the good format of HTML is very important.

If the browser receives a document that is not well-formed, it will do its best. The resulting tree structure in the best case will be the original page that the author wants to approximate, and at worst will be unrecognizable. If you've ever loaded a page into a browser and you see a completely unexpected result, you may wonder what your structure should be when you see the browser's results and continue working with frustration. Of course, it's pretty straightforward to fix this: Make sure the document is well-formed! If you are not sure how to write standardized HTML, consult your resources for assistance.

Introduction to DOM

So far, you've known that browsers convert Web pages to object representations, and you might even guess that the object representation is a DOM tree. The DOM represents Document Object Model, a specification that can be obtained from the World Wide Web Consortium (you can see some of the DOM related links in resources).

But more importantly, the DOM defines the object's type and properties, allowing the browser to represent markup. (The next article in this series will specifically describe the specification for using DOM in JavaScript and Ajax code.) )

Document objects

First, you need to access the object model itself. This is very easy; To use the built-in document variable in any JavaScript code running on a Web page, you can write the following code:

var domtree = document;

Of course, the code itself is of little use, but it demonstrates that each Web browser makes the Document object available to JavaScript code and demonstrates the complete tree of the object representation tag (Figure 1).

Each item is a node

Obviously, the document object is important, but this is just the beginning. Before you go further, you need to learn another term: a 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 particular type of object, a DOM node. More specific types, such as text, elements, and attributes, inherit from this basic node type. So you can have text nodes, element nodes, and attribute nodes.

If you already have a lot of JavaScript programming experience, you might already be using DOM code. If you've been tracking this Ajax series so far, you'll have to use DOM code for some time now. For example, the code line var number = document.getElementById ("Phone"). Value; Use the DOM to find a specific element, and then retrieve the value of the element (in this case, a form field). So even if you don't realize this, you'll use DOM every time you type the document into JavaScript code.

To explain in detail the terminology that has been learned, a DOM tree is a tree of objects, but more specifically, it is a tree of node objects. In Ajax applications or in any other JavaScript, these nodes can be used to produce the following effects, such as removing elements and their contents, highlighting specific text, or adding new image elements. Because they all occur on the client (code that runs in the Web browser), these effects occur immediately without communicating with the server. The end result is usually that the application feels more responsive because the content changes on the Web page do not have a long pause when the request is turned to the server and the response is interpreted.

In most programming languages, you need to learn the actual object names of each node type, learn the available attributes, and figure out the types and casts, but this is not required in JavaScript. You can create only one variable and assign it to the object you want (as you've seen):

var domtree = document;
var phonenumberelement = document.getElementById ("Phone");
var phonenumber = Phonenumberelement.value;

No type, JavaScript creates variables and assigns the correct type to them as needed. As a result, using DOM from JavaScript becomes trivial (an article in the future will be more ingenious when it is devoted to XML-related DOM).

Conclusion

Here, I want to leave you a little suspense. Obviously, this is not a fully detailed description of the DOM; in fact, this article is simply an introduction to DOM. DOM's content is much more than what I'm introducing today!

The next article in this series expands on these ideas and delves into how to use DOM in JavaScript to update Web pages, quickly change HTML, and create a more interactive experience for your users. In a later article 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.

In this case, it would be easy to get a better understanding of the DOM, such as detailing how to move through the DOM tree, getting the values of elements and text, traversing the list of nodes, and so on, but this might give you the impression that DOM is about code, and in fact it is not.

Before reading the next article, try to think about the tree structure and practice it with some of your own HTML to see how the Web browser transforms HTML into a tagged tree view. Also, think about the organization of the DOM tree and practice it in the special case described in this article: attributes, text with elements mixed in it, elements with no text content (such as an IMG element).

If you have a solid grasp of these concepts and then learn the syntax of JavaScript and DOM (the next article), it makes the response easier.

And don't forget, here are the answers to listings 2 and 3, which also contain sample code!

Figure 2. The answer to listing 2

Figure 3. The answer to listing 3


(Click this image to enlarge)



Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.