Document Object Model

Source: Internet
Author: User

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.

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.

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.

Web JavaScript Script Element

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

      



JavaScript!




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:

 
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.

 leftSide = 100;  
topSide = 50;
areaOfRectangle = leftSide * topSide;
String

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

 firstPart = 'Hello';  
secondPart = 'World!';
allOfIt = firstPart + ' ' + secondPart; //
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); // veryTired = ;
(veryTired) {
}

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

Function

A function is a special object.

 myFunctionName(arg1, arg2) {
}

(arg1, arg2) {
}

//myFunctionName(); myFunctionName('foo', 'bar');

( () {
})();
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:


fruit = ['apple', 'lemon', 'banana'];

fruit = Array('apple', 'lemon', 'banana');

fruit[0]; fruit[1]; fruit[2];
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.


profile = {
name: 'Bob',
age: 99,
job: 'Freelance Hitman'
};

profile = 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:

 legalDrinkingAge = 21;  
yourAge = 29;

( yourAge >= legalDrinkingAge ) {
alert('You can drink.');
} {
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:

 someMaths = 2 + 3 + 4 - 10 * 100 / 2;  

( 2 == (5 - 3 ) { }
( 2 != (5 - 3 ) { }

2 === 2 2 !== 3
numberOfFruit = 9;
numberOfFruit -= 2; 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.

 envatoTutSites = ['NETTUTS', 'PSDTUTS', 'AUDIOTUTS', 'AETUTS', 'VECTORTUTS'];

counter = 0;
lengthOfArray = envatoTutSites.length;
(counter < lengthOfArray) {
alert(envatoTutSites[counter]);
counter++; }

// ( 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.

  



JavaScript!



My first paragraph...


List item 1
List item 1
List item 1
List item 1
List item 1





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

 introParagraph = document.getElementById('intro');  

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:

 allUnorderedLists = document.getElementsByTagName('ul');  
//
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:

 unorderedList = document.getElementsByTagName('ul')[0];

allListItems = unorderedList.getElementsByTagName('li');

( i = 0, length = allListItems.length; i < length; i++) {
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:

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 chapter, we only list some examples. In the next chapter, we will list more examples, including browser event models.

Http://www.cnblogs.com/TomXu/archive/2012/02/16/2351331.html

Related Article

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.