JavaScript and Dom (top)

Source: Internet
Author: User
Tags add numbers cdata

I would have written an article like myself ... The result saw Tom uncle this article. The summary is really great, other articles are very good recommended

Reprinted from: http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html

Document Object Model

The DOM (Document Object model) is an API that interacts with JavaScript for content. JavaScript and Dom are often used as a whole, because JavaScript is usually for DOM manipulation and interaction.

Main content from: http://net.tutsplus.com/tutorials/javascript-ajax/javascript-and-the-dom-series-lesson-1/

With regard to DOM, some knowledge needs to be noted:
1. The Window object acts as a global object, which means that you can access the Global object through window.

    1. Properties are stored as variables under the object, and all global objects created on the page become properties of the Window object.
    2. Methods are stored as functions under the object, because the left and right functions are stored under the Window object, so they can also be called methods.

2. Dom creates hierarchical results for Web documents, which are made up of node nodes, and there are several DOM node types, the most important being element, Text, and document.

    1. The element node shows a component on the page, so if you have a paragraph element (<p>), you can access it through this DOM node.
    2. The text node displays all of the textual elements in the page, so if your paragraph has text in it, you can access the text directly from the DOM's text node.
    3. The document node represents the entire documentation, which is the root node of the DOM.

3. Each engine has a slightly different implementation of the DOM standard. For example, the Gecko engine used by the Firefox browser has a good implementation (although not fully compliant), but the implementation of the Trident engine used by IE is incomplete and has bugs, which brings a lot of problems to the development.

If you are using Firefox, I recommend that you download the Firebug plugin now, which is useful for you to understand the DOM structure.

JavaScript on the Web SCRIPT Element

When you use JavaScript on a Web page, you need to use the SCRIPT element:

  <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >      //  <![ cdata[                    //  ]]>              </script>                </body>      < /html>  

The above code, strictly speaking script's Type property should be set to Application/javascript, but because IE does not support this, so usually we have to write text/javascript or directly remove the type. Alternatively you can see the comment line in the SCRIPT element//<! [cdata[is used to tell an XHTML-enabled browser that the code is character data rather than XHTML tags, such as if your data in it uses < or, the browser will no longer parse into XHTML tags.

Defer Property

Any code declared in the script element will run when the page is loaded, with the exception of adding a defer attribute to the script element. The Defer property tells the browser to execute the JS code after loading the HTML document, but this property can only be used under IE.

Connecting external Scripts

If you want to learn about external scripts, simply use the SRC attribute on the script, the advantage of using a separate JS file is that it can be cached, and you don't have to worry about CDATA issues:

<script type= "Text/javascript" src= "My-script.js" ></script>
JavaScript Prerequisites

Before we move on to the DOM, let's review the core knowledge of JavaScript, if you don't know it, it's okay, we'll take a little bit of time to review it in this section.

JavaScript has several data types: number, String, Boolean, Object, Undefined, and Null.

Single-line comments use a double slash//, all text behind a double slash is commented out, and multiple lines are noted using/* and */surround.

Number

All numbers in JavaScript are floating-point, and when declaring a number variable, remember not to use any quotation marks.

// Note: Declaring variables with the Var class var leftside = +;   var topside =;   var // =  
String

It is very simple to declare strings in JavaScript, as in other languages, using single or double quotes in JS.

var firstpart = ' Hello ';   var secondpart = ' world! ' ;   var // Hello world!   // + Match is a character connector. Also used to add numbers
Boolean

A Boolean type is used for conditional judgment, and the Boolean type is only 2 values: True and False. Any comparison using logical operators will return a Boolean value.

// = True   // You can also assign a Boolean value to a variable var true ; // this uses if (verytired) {    //}   

= = = is also a comparison operator, not only comparing values, but also comparing types.

Function

The function is a special object.

//declaring a new function using the function operatorfunctionmyfunctionname (arg1, arg2) {//function Code}//You can also declare anonymous functionsfunction(Arg1, arg2) {//Function code goes here. }//running the function is simple, just add parentheses to the function name.//or you can take the parameters.Myfunctionname ();//No referenceMyfunctionname (' foo ', ' Bar ');//with Parameters//You can also use self-invoking(function () {    //The function is called from here})();
Array

An array is also a special object that contains a batch of values (or objects) that require a numeric index to access the data:

// 2 ways of declaring an array // literal:   var fruit = [' apple ', ' lemon ', ' banana ']; // Array constructor:   var New Array (' apple ', ' lemon ', ' banana '); fruit[//  Access 1th item (apple)  //  Access 2nd item (lemon)  //
Object

An object is a collection of key-value, and arrays are similar, and the only difference is that you can define a name for each data.

// 2 Types Define object objects // literal (curly braces) var profile = {    ' Bob ',    hitman,    ' Freelance '}; // using the object constructor var New  = ' Bob '= hitman= ' Freelance ';  
if/else Statements

The most used statement in JS is the conditional statement:

var legaldrinkingage = +;   var yourage =;     if (Yourage >= legaldrinkingage) {       alert (' You can drink. ') );   Else {      alert (' Sorry, you cannot drink. ');  
JavaScript Operators

I suggest you visit this page to see all the JS operators, here I just give some examples:

//SubtractionvarSomemaths = 2 + 3 + 4-10 * 100/2; //equalsif(2 = = (5-3) {/*Code*/}//= = comparison is equal      //Not equal toif(2! = (5-3) {/*Code*/ }         //strictly equals (recommended)2 = = = 2//instead of 2 = = 22!== 3//instead of 2! = 3      //Assignment Value:varNumberoffruit = 9; Numberoffruit-= 2;//equivalent to "numberoffruit = numberOfFruit-2"Numberoffruit + = 2;//equivalent to "numberoffruit = Numberoffruit + 2"
Loop Loop

Loop loops are handy when iterating through arrays or all of the members of an object, and the most used in JavaScript is for and while statements.

varEnvatotutsites = [' NETTUTS ', ' psdtuts ', ' audiotuts ', ' aetuts ', ' vectortuts '];//While LoopvarCounter = 0;varLengthofarray =envatotutsites.length; while(Counter <Lengthofarray)    {alert (envatotutsites[counter]); Counter++;//equivalent to counter + = 1; }//For Loop//I just used to iterate, can be arbitrarily named for(vari = 0, length = envatotutsites.length; i < length; i++) {alert (envatotutsites[i]);} 
Dom Body Accessing DOM nodes

Let's take an example where an HTML contains a text and an unordered list.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" > < HTML xmlns= "http://www.w3.org/1999/xhtml" lang= "en" > //<! [Cdata[          //]]></script> </body> 

In the example above, we use the getElementById Dom method to access the P-paragraph and add the following code to the script:

var introparagraph = document.getElementById (' intro ');   // now that the DOM node is present, this DOM node is showing this paragraph of information

The variable introparagraph is now referenced to the DOM node, and we can do a lot of things with that node, such as querying content and properties, or anything else, even deleting it, cloning it, or moving it to other nodes in the DOM tree.

Anything on the document, we can use JavaScript and DOM API to access, so similarly, we can also access the above unordered list, the only problem is that the element does not have an id attribute, if the ID of the words can be used the same way, or use the following getElementsByTagName method:

var allunorderedlists = document.getElementsByTagName (' ul ');   // ' getElementsByTagName ' returns a collection of nodes // -the array is a bit similar
getElementsByTagName

The getElementsByTagName method returns a collection of nodes, and arrays similar to the length property, and one important feature is that he is live--if you add a new Li element to the element, the collection is automatically updated, between him and the array type, So it can be accessed in the same way as an array of accesses, so starting with 0:

// Access unordered list: [0] Index var unorderedlist = document.getElementsByTagName (' ul ') [0]; // get all the Li collections:   var alllistitems = unorderedlist.getelementsbytagname (' li '); // Looping through  for (var i = 0, length = alllistitems.length; i < length; i++) {    //  pops up the text content of the node     

The knowledge gained by DOM is more clearly demonstrated in an example:

Dom Shuttle

The word "shuttle" is primarily used to describe finding nodes through the DOM, which provides a number of node properties that allow us to go up and down and query the nodes.

All nodes have these properties and can be used to access the associated node nodes:

    1. node.childnodes: Accesses all the immediate child node elements under a cell, which can be a loop-like array object. The node collection can protect child nodes of different types (such as text nodes or other element nodes).
    2. Node.firstchild: The first item (' Element.childnodes[0] ') with the ' ChildNodes ' array is the same effect, just a shortcut.
    3. Node.lastchild: The last item in the ' ChildNodes ' array (' element.childnodes[element.childnodes.length-1] ') is the same effect, just a shortcut. Shortcut.
    4. node.parentnode: Access the parent node of the current node, only one parent node, and the ancestor node can be accessed in the form of ' Node.parentNode.parentNode '.
    5. node.nextsibling: Accesses the next node at the same level as the current node on the DOM tree.
    6. node.previoussibling: Accesses the previous node on the DOM tree at the same sibling as the current node.

Through this diagram, it is much simpler to understand, but there is a very important point of knowledge: that is, there is no space between elements, if there is a space between the UL and Li, it will be considered as the content of the empty text node, so ul.childnodes[0] is not the first LI element. The next node of the corresponding,<p> is also not <ul> because there is a blank line between <p> and <ul>, it is common for this situation to traverse all the child nodes and then judge the NodeType type, 1 is the element, 2 is the attribute, 3 is the text node, and the detailed type can be obtained by this address:

    Node.element_node = =    1 =    = 2    = =    3 =    = 4 = 5 = = 6     = =    7 =    =    8 = = 9 = =           = = 12
Summarize

Native DOM methods and properties are sufficient for our daily use, and we have just a few examples in this section, and we'll include more examples in the next section, as well as a browser event model.

JavaScript and Dom (top)

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.