Deep understanding of the JavaScript series (23): JavaScript and DOM (on) -- also applies to beginners, javascriptdom

Source: Internet
Author: User
Tags add numbers

Deep understanding of the JavaScript series (23): JavaScript and DOM (on) -- also applies to beginners, javascriptdom
Document Object Model

DOM (Document Object Model) is an API for content interaction with JavaScript. Javascript and DOM are usually taken as a whole, because Javascript is usually used for DOM operations and interaction.

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

For DOM, note the following:
1. The window object is a global object, that is, you can access the global object through the window.

  1. Attributes are stored in the form of variables under the object. All global objects created on the page will become properties of the window object.
  2. Methods are stored in the form of functions under the object, because the left and right functions are stored in the window object, so they can also be called methods.

2. DOM creates hierarchical results for web documents. These levels are composed of node nodes. Here there are several DOM node types, most importantly, Element, Text, and Document.

  1. An Element is displayed 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 Text-related elements on the page. Therefore, if your section contains Text, you can directly access the Text through the DOM Text node.
  3. The Document node represents the entire Document and is the root node of the DOM.

3. Each engine has slightly different implementations of the DOM standard. For example, the Gecko engine used by Firefox has good implementation (although it does not fully comply with W3C specifications), the implementation of the Trident engine used by IE is incomplete and there are bugs, it brings many problems to developers.

If you are using Firefox, we recommend that you download the Firebug plug-in immediately, which is very useful for you to understand the DOM structure.

Web JavaScript Script Element

When using JavaScript on a website 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">      

Strictly speaking, the TYPE attribute of the SCRIPT should be set to application/javascript. However, because IE does not support this attribute, we usually have to write text/javascript or directly remove the type. In addition, you can also see the comment row in the SCRIPT element. // <! [CDATA [is used to tell browsers that support XHTML. The code here is character data rather than XHTML labels. For example, if you use the data in it <or>, the browser will not parse it into XHTML labels.

Defer attributes

Any code declared in the SCRIPT element will run during page loading. The only exception is to add a defer attribute to the SCRIPT element. The defer attribute tells the browser to execute JS Code after loading the HTML document, but this attribute can only be used in IE.

Connect external scripts

If you want to know 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, in addition, you do not need to worry about CDATA issues:

<script type="text/javascript" src="my-script.js"></script>
JavaScript required

Before proceeding to DOM, let's review the essential knowledge of JavaScript. If you do not know it, it doesn't matter. We will take some time to review it in this chapter.

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

A single line comment uses a double slash //. All the text after the double slash will be commented out. Use/* and */to enclose multiple lines.

Number

In JavaScript, all numbers are float. Do not use any quotation marks when declaring a numeric variable.

// Note: Use the var class to declare the variable var leftSide = 100; var topSide = 50; var areaOfRectangle = leftSide * topSide; // = 5000
String

It is very easy to declare strings in JavaScript. Like other languages, you can use single quotes or double quotes in JavaScript.

Var firstPart = 'hello'; var secondPart = 'World! '; Var allOfIt = firstPart + ''+ secondPart; // Hello World! // + Match the character connector. It is also used to add numbers.
Boolean

Boolean is used for condition determination. boolean has only two values: true and false. Any comparison using logical operators returns a Boolean value.

5 === (3 + 2); // = true // You can also assign a Boolean value to the variable var veryTired = true; // use if (veryTired) like this) {// execute code}

===Is also a comparison operator, not only a numerical value, but also a comparison type.

Function

A function is a special object.

// Use the function operator to declare the new function myFunctionName (arg1, arg2) {// function Code} // You can also declare an anonymous function (arg1, arg2) {// Function code goes here .} // It is very easy to run a function. You can simply add parentheses after the function name. // or you can also add the parameter myFunctionName (); // No parameter myFunctionName ('foo ', 'bar'); // There are parameters // You can also use the self-called function () {// here the self-called function })();
Array

An array is also a special object that contains a batch of values (or objects). To access the data, you need to use a digital index:

// Two methods to declare an Array // literal: var fruit = ['apple', 'limon', 'Banana ']; // Array constructor: var fruit = new Array ('apple', 'limon', 'bana'); fruit [0]; // access 1st items (apple) fruit [1]; // access 2nd items (lemon) fruit [2]; // access 3rd items (banana)
Object

An object is a set of key-value, similar to an array. The only difference is that you can define a name for each data.

// Define two types of Object objects // literal (braces) var profile = {name: 'bob', age: 99, job: 'Freelance Hitman '}; // use the Object constructor var profile = new Object (); profile. name = 'bob'; profile. age = 99; profile. job = 'Freelance Hitman ';
IF/Else statement

The most commonly used statement in JS is a condition statement:

var legalDrinkingAge = 21;  var yourAge = 29;    if ( yourAge >= legalDrinkingAge ) {       alert('You can drink.');  } else {      alert('Sorry, you cannot drink.');  
JavaScript Operators

We recommend that you visit this page to view all JS operators. Here I will just give some examples:

// Add, subtract, multiply, and divide var someMaths = 2 + 3 + 4-10*100/2; // equals to if (2 = (5-3) {/* Code */} // = compare whether it is equal/not equal to if (2! = (5-3) {/* Code */} // strictly equal to (recommended) 2 = 2 // replace 2 = 2 2! = 3 // replace 2! = 3 // Value assignment: var numberOfFruit = 9; numberOfFruit-= 2; // equivalent to "numberOfFruit = numberOfFruit-2" numberOfFruit + = 2; // It is equivalent to "numberOfFruit = numberOfFruit + 2"
Loop

Loop loops are convenient when traversing an array or all the members of an object. JavaScript uses the most FOR and WHILE statements.

Var envatoTutSites = ['netuts', 'psuts', 'audiotuts ', 'aetuts', 'vectortuts ']; // while loop var counter = 0; var lengthOfArray = envatoTutSites. length; while (counter <lengthOfArray) {alert (envatoTutSites [counter]); counter ++; // equivalent to counter + = 1 ;} // FOR Loop // I is only used for iteration and can be named FOR (var I = 0, length = envatoTutSites. length; I <length; I ++) {alert (envatoTutSites [I]);}
DOM body Access DOM nodes

Let's take an example. An HTML contains a piece of 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">  

In the above example, we use the getElementById DOM method to access the p section and add the following code to the SCRIPT:

Var introParagraph = document. getElementById ('intro'); // The DOM node displays the Information Section.

The variable introParagraph has now been referenced on this DOM node. We can do a lot of things on this node, such as querying the content and attributes, or performing any other operations, or even deleting it and cloning it, or move it to another node in the DOM tree.

We can use JavaScript and DOM APIs to access any content in the document. Similarly, we can also access the unordered list above. The only problem is that the element has no ID attribute, if the ID is used, you can use the same method, or the following getElementsByTagName method:

Var allUnorderedLists = document. getElementsByTagName ('ul '); // 'getelementsbytagname' returns a node set //-a little similar to an array
GetElementsByTagName

The getElementsByTagName method returns a node set with a length attribute similar to an array. An important feature is that it is live-if you add a new li element to the element, this set will be automatically updated, between him and the array type, so you can access it in the same way as accessing the array, so it starts from 0:

// Access the unordered list: [0] index var unorderedList = document. getElementsByTagName ('ul ') [0]; // obtain all the li sets: var allListItems = unorderedList. getElementsByTagName ('lil'); // looping for (var I = 0, length = allListItems. length; I <length; I ++) {// The text content of the node alert (allListItems [I]. firstChild. data );}

The following example shows the knowledge of DOM:

DOM shuttle

The word "Shuttle" is mainly used to describe nodes through DOM. dom api provides a large number of node attributes for us to query nodes up or down.

All nodes have these attributes and can be used to access related node nodes:

  1. Node. childNodes: Access all direct subnode elements under a single element. It can be a cyclable array object. This node set can protect different types of subnodes (such as text nodes or other element nodes ).
  2. Node. firstChild: The same effect as the first entry of the 'childnodes 'array ('element. childNodes [0]') is just a shortcut.
  3. Node. lastChild: The same effect as the last entry of the 'childnodes 'array ('element. childNodes [Element. childNodes. length-1]') is just a shortcut. Shortcut cut.
  4. Node. parentNode: Access the parent Node of the current Node. Only one parent Node can be accessed. The parent Node can be accessed in the form of 'node. parentNode. parentnode.
  5. Node. nextSibling: Access the next node on the DOM tree at the same level as the current node.
  6. Node. previussibling: Access the previous node on the DOM tree at the same level as the current node.

This figure is much simpler to understand, but there is a very important point: there cannot be spaces between elements. If there is a space between ul and li, it will be considered as a text node with empty content, so ul. childNodes [0] is not the first li element. Correspondingly, the next node of <p> is not <ul> because there is an empty row between <p> and <ul>, in this case, we usually need to traverse all the sub-nodes and then judge the nodeType type. 1 is the element, 2 is the attribute, and 3 is the text node. For the detailed type, we can use this address:

    Node.ELEMENT_NODE == 1    Node.ATTRIBUTE_NODE == 2    Node.TEXT_NODE == 3    Node.CDATA_SECTION_NODE == 4    Node.ENTITY_REFERENCE_NODE == 5    Node.ENTITY_NODE == 6    Node.PROCESSING_INSTRUCTION_NODE == 7    Node.COMMENT_NODE == 8    Node.DOCUMENT_NODE == 9    Node.DOCUMENT_TYPE_NODE == 10    Node.DOCUMENT_FRAGMENT_NODE == 11    Node.NOTATION_NODE == 12
Summary

Native DOM methods and attributes are enough for our daily application. In this section, we only list some examples. In the next section, we will list more examples, including browser event models.

Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.

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.