In-depth understanding of the JavaScript series: JavaScript and Dom (UP) – Also for beginners

Source: Internet
Author: User
Tags add numbers cdata

The Document Object model, Document Object Modeldom, 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. The main content is 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:1the. Window object acts as a global object, which means that you can access the Global object through window. Properties are stored as variables under the object, and all global objects created on the page become properties of the Window object. 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. The element node shows a component in the page, so if you have a paragraph element (<p>), which you can access through this DOM node. The text node displays all of the textual elements in the page, so if your paragraph has text inside it, you can access it directly through the text node of the DOM, which represents the entire document, which is the root node of the DOM. 3each 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. Javascriptscript elements on the web 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> The above code, strictly speaking, the Type property of the script 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. Also you can see the comment lines 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 loads, 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 there is no need 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 double slash//, all the text behind the double slash is commented out, and multiple lines are noted using/* and/*. number in JavaScript all numbers are floating point type, when declaring a numeric variable, remember not to use any quotation marks. //Note: Declaring variables with the Var classvarLeftside = 100; varTopside = 50; varAreaofrectangle = Leftside * topside;//=The Stringjavascript declaration string is particularly simple, as in other languages, using either single or double quotes in JS. varFirstpart = ' Hello '; varSecondpart = ' world! '; varAllofit = Firstpart + "+ secondpart;//Hello world! //+ Match is a character connector. Also used to add numbersA Boolean 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. 5 = = = (3 + 2);//= True//You can also assign a Boolean value to a variablevarverytired =true;//this usesif(verytired) {//Execute Code}   ===is also a comparison operator, not only comparing values, but also comparing types. function functions are special objects. //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 arrays are also special objects that contain a number of values (or objects) that require the use of a numeric index to access the data://2 ways of declaring an array//literal:varFruit = [' apple ', ' lemon ', ' banana '];//Array constructor:varFruit =NewArray (' apple ', ' lemon ', ' banana '); fruit[0];//Access 1th Item (apple)FRUIT[1];//Access 2nd item (lemon)FRUIT[2];//Access 3rd Item (banana)object is a key-The collection of value, and the similarity of the array, the only difference is that you can define a name for each data. //2 Types Define object objects//literal (curly braces)varProfile ={name:' Bob ', Age:99, Job:' Freelance hitman '};//using the object constructorvarProfile =NewObject ();p rofile.name= ' Bob ';p rofile.age= 99;p rofile.job= ' Freelance hitman '; IF/else statementsthe most used statement in JS is the conditional statement:varLegaldrinkingage = 21; varYourage = 29; if(Yourage >=legaldrinkingage) {Alert (' You can drink. '); } Else{alert (' Sorry, you cannot drink. '); The JavaScript operator suggests that you visit this page to see all of the JS operators, and here are just a few 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 loops 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 Access DOM node We have 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:varIntroparagraph = document.getElementById (' intro ')); //now that the DOM node is present, this DOM node is showing this paragraph of informationThe 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:varallunorderedlists = document.getElementsByTagName (' ul '); //' getElementsByTagName ' returns a collection of nodes//-the array is a bit similarThe Getelementsbytagnamegetelementsbytagname method returns a collection of nodes, and arrays similar to the length property, an important feature is that he is live-if you add a new Li element to the element, This collection is automatically updated, between him and the array type, so that it can be accessed in the same way as accessing arrays, so starting with 0://Access unordered list: [0] IndexvarUnorderedlist = document.getElementsByTagName (' ul ') [0];//get all the Li collections:varAlllistitems = unorderedlist.getelementsbytagname (' li ');//Looping through for(vari = 0, length = alllistitems.length; i < length; i++) {    //pops the text content of the nodealert (alllistitems[i].firstchild.data);} A more clear example of what DOM gets: the DOM Shuttle "shuttle" is mainly used to describe the discovery of nodes through the DOM, and the DOM API provides a number of node properties that allow us to go up and down and query the nodes. All nodes have these properties, all of which can be used to access the associated node node: Node.childnodes: Accesses all the immediate child node elements under a single element, 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). Node.firstchild: The first entry with the ' ChildNodes ' array (' element.childnodes[0] is the same effect, just a shortcut. Node.lastchild: The last item in the array with ' childNodes ' (' Element.childnodes[element.childnodes.length-1] is the same effect, just a shortcut. Shortcut. 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 '. Node.nextsibling: Accesses the next node at the same level as the current node on the DOM tree. Node.previoussibling: Accesses the previous node on the DOM tree at the same sibling as the current node. Through this diagram, it is much easier 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 to be the content of the empty text node, so ul.childnodes[0] It is not the first LI element. Correspondingly,<p> the next node is also not <ul> because <p> and <ul>there is an empty row between the nodes, generally encountered this situation need to traverse all the child nodes and then determine the NodeType type, 1 is the element, 2 is the property, 3 is the text node, the detailed type can pass this address: Node.element_node= = 1Node.attribute_node= = 2Node.text_node= = 3Node.cdata_section_node= = 4Node.entity_reference_node= = 5Node.entity_node= = 6Node.processing_instruction_node= = 7Node.comment_node= = 8Node.document_node= = 9Node.document_type_node= = 10Node.document_fragment_node= = 11Node.notation_node= = 12summarizing native DOM methods and properties is enough for our daily use, this chapter is just a list of examples, and we'll include more examples in the next section, as well as a browser event model. Synchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of the JavaScript series: JavaScript and Dom (UP) – Also for beginners

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.