Use dom for Web response

Source: Internet
Author: User
Tags image flip
Use dom for Web response

The watershed between programmers (using backend applications) and web programmers (compiling HTML, CSS, and JavaScript) is long-lasting. However, the Document Object Model (DOM) makes up for this crack, making it extremely effective to use HTML at the front end while using XML at the back end. 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:

  • 1. Some people (usually you !) Create HTML in a text editor or IDE.
  • 2. Then you upload HTML to the Web server, such as Apache httpd, and publish it on the internet or intranet.
  • 3. the user requests your web page using Firefox, Safaria, and other browsers.
  • 4. Your browser requests HTML from your server.
  • 5. 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 a web browser directory, you usually think that it has been "done" and (hopefully) think that it will never be considered 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 design the page style as much as you can, it is by no means the biggest impact on Web pages.

What you absolutely control is the structure of the web page. 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. The text is not considered as a large font size, black, or bold type, but H1 is considered as a 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 be aware that only the markup can provide this level of organization; P indicates that the text is in the paragraph, IMG indicates the image, div divides the page into sections, and so on.

It should also be clear that styles and behaviors (event handlers and JavaScript) are applied to the Organization afterwards. 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.

Advantages of text tagging

Before discussing Web browsers, it is worth considering why plain text is the best choice for storing HTML. 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, the code is coming soon, but you need to restrain your impatience in coding, because it is 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, if you want to input text (text-align: center) in the P element of the center-text class, how can we 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. With the ability of JavaScript to change the Page Structure, things become 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 <P> welcome to a <em> really </em> boring page. </P>
<Div>
Come again soon.

</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 begins with the outermost HTML inclusion element, that is, the HTML element. The tree is called the root 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. The head and body elements are children of the HTML root element; the title is the child of the head, and the text "trees, trees, everywhere" is the child of the title. The entire tree is organized in this way until the browser obtains a structure similar to figure 1.

Additional Terms

To keep the tree analogy, head and body are called HTML branches ). 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"; these are usually called leaves because 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 example, elements in HTML are represented by the element object type. The text in the document is represented by the text type, the attribute is represented by the attribute type, 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, followed by Angle brackets and escape sequences (for example, use <representation <, use> representation>) and other things are no longer a problem. 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 have style attributes, so it is very easy to quickly change the style of elements or text segments. For example, you need to use JavaScript to change the DIV height, as shown below:

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 an article that contains very little code), if you want to manipulate these trees, you need to be familiar with their structure.

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

  • What happened to the property?
  • What about text decomposed into elements (such as Em and B?
  • The structure is incorrect (for example, when the end p Mark is missing). What 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 will be found in Listing 1 and figure 1. First, let's look at how P elements are decomposed. If you ask a common web developer "what is the text content of P elements", 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.

In fact, the P element has three different sub-objects, and none of them 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 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, the P element has three different parts:

  • Text before the EM Element
  • Em element itself
  • Text after the EM Element

If this order is disrupted, the emphasis may be placed on the text error section. To keep everything normal, the P element has three sub-objects in the order shown in the HTML in Listing 1. Moreover, the key text "really" is not a child element of P, but a child element of the child element em of P.

Understanding this concept is very important. Although the "really" text may be displayed together with other P element texts, it is still a direct child element of the EM element. It can be in different formats from other P texts 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
<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"> </a> wowould
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. Therefore, the DIV 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 will see in the next article, you can call methods such as getattribute ("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. The P element can have multiple em elements, so the 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 format is a term widely used in XML, which has two basic meanings:

  • Each start tag has a matched end tag. Therefore, each <p> matches </P> In the document, each <div> matches </div>, 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. Therefore, <B> <I> bold and italics </B> </I> is invalid, because the start Mark <I> in the innermost part does not match the end mark <B> in the innermost part. To make it in good format, either switch the start marking order or switch the end Marking 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. Therefore, for example, if the text font in element B is different from that in element I, then 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 mark the code.

Document Object

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 the web page, you can write the following code:

VaR domtree = document;

Of course, this code is useless, but it demonstrates that each web browser makes the Document Object available for JavaScript code and demonstrates the complete tree of the object that represents the mark (figure 1 ).

Each item is a node

Obviously, the document object is 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 far, you must use Dom code for a while. For example, the code line var number = document. getelementbyid ("phone "). value; Use 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 this, the Dom is used every time you type the document into JavaScript code.

I have explained in detail the terms I have learned. The DOM tree is the tree of objects, but more specifically, it is the tree of node objects. 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 most programming languages, you need to learn the actual object names of each node type, learn available attributes, and clarify the types and forced conversions. However, 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!

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.

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

 

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.