JavaScript---JavaScript and dom

Source: Internet
Author: User
Tags access properties

JavaScript and DOM:

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

<PID= "Intro">My First paragraph ...</P>  <ul>        <Li>List Item 1</Li>        <Li>List Item 1</Li>        <Li>List Item 1</Li>        <Li>List Item 1</Li>        <Li>List Item 1</Li>  </ul>  

In the example above, we use the getElementById Dom method to access the P-paragraph.

var // now that the DOM node is present, this DOM node is showing this paragraph of information

The variable pdom 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 allU = document.getElementsByTagName (' ul ');  // ' getElementsByTagName ' returns a collection of nodes-and the array is somewhat similar
getElementsByTagName

The getElementsByTagName method returns a collection of nodes, and arrays similar to the length property, and an important feature is that he is real-time-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
manipulating elements

Each DOM node includes a collection of attributes, and most of the properties provide an abstraction for the appropriate functionality. For example, if you have a text element with an id attribute intro, you can easily change the color of the element through the DOM API:

document.getElementById (' intro '). Style.color = ' #FF0000 ';

In order to understand the functionality of this API, it is very easy to understand how to do this in a separate step-by-step perspective:

var myDocument = document;   var myintro = Mydocument.getelementbyid (' intro ');   var myintrostyles = myintro.style;     // now, we can set the color:   Myintrostyles.color = ' #FF0000 ';

Now that we have a reference to the text's style object, we can add another CSS style:

myintrostyles.padding = ' 2px 3px 0 3px ';   = ' #FFF ';  

Here we just want the basic CSS property name, the only difference is that the name of the CSS property if it comes with--it needs to be removed, such as using margintop instead of margin-top. For example, the following code is not working and throws a syntax error:

Myintrostyles.padding-top = ' 10em ';        // A syntax error has occurred: // in JavaScript, horizontal-is the subtraction operator. // and there's no such attribute name

Properties can be accessed like arrays, so using this knowledge we can create a function to change the style of any given element:

function Changestyle (Elem, property, Val) {    //  Use [] to access Properties }//  Use the above functions:   var // Gets the intro text object changestyle (myintro, ' Color ', ' red ');  

Usually DOM operations change the original content, there are several ways to implement this, the simplest is to use the innerHTML property, for example:

var myintro = document.getElementById (' intro ');     // Replace current content myintro.innerhtml = ' New content for the <strong>amazing</strong> paragraph! ' ;     //  myintro.innerhtml + = ' ... some more content ... ';

The only problem is that the method is not defined in the specification and is not defined in the DOM specification, and if you do not resent it, please continue to use it, because it is much faster than the other methods we are going to discuss below.

node Nodes
var myintro = document.getElementById (' intro ');     // Add Content var sometext = ' This was the text I want to add ';   var textnode = document.createTextNode (sometext);  Myintro.appendchild (textnode);

Here we use the AppendChild method to attach the new text node attachment to the Text field, which is a bit longer than the nonstandard innerHTML method, but it is still important to understand these principles, here is a more detailed example of using DOM methods:

 var  Myintro = document.getElementById (' intro '    );  //  add new connection to text node  //  var  mynewlink = Document.createelement (' a '); //  <a/>  mynewlink.href = ' http://google.com '; //  <a href=" http://google.com "/>  mynewlink.appendchild ( document.createTextNode (' Visit Google ' ));  //  <a href= "http://google.com" > Visit google</a>   content attachments to text nodes  Myintro.appendchild (mynewlink); 

There is also a InsertBefore method used in the DOM to re-node the contents of the previous attachment, through InsertBefore and appendchild we can implement their own InsertAfter function:

// ' Target ' is an existing element in the DOM . // ' Bullet ' is the new element  to insert function InsertAfter (target, bullet) {      ?           Target.parentNode.insertBefore (bullet, target.nextsibling)          : Target.parentNode.appendChild (bullet);  }     //  use 3 mesh expression:  //  format: condition? expression when the condition is true: expression when condition is false

The above function first checks to see if the target element's sibling next node exists, if there is a bullet node in front of the node, if it does not exist, it means that the target is the last node, directly behind the append new node. The DOM API doesn't provide InsertAfter because it's really unnecessary-we can create it ourselves.

Dom operations have a lot of content, and what you see above is just part of it.

Event Events

Browser events are the core of all Web programs, and through these events we define what is going to happen, and if there is a button on the page, you need to verify that the form is legitimate before clicking on it, then you can use the Click event, the most standard list of events listed below:

Note: As we said in the previous chapter, the DOM and JavaScript languages are 2 separate things, and browser events are part of the DOM API, not part of JavaScript.

Mouse Events
    1. 'MouseDown' – the mouse device triggers the MouseDown event when an element is pressed.
    2. 'MouseUp' – Triggers the MouseUp event when the mouse device bounces from the pressed element.
    3. 'Click' – The Click event is triggered when the mouse clicks on an element.
    4. 'DblClick' – The DblClick event is triggered when the mouse double-clicks the element.
    5. 'mouseover' – Triggers the MouseOver event when the mouse moves over an element.
    6. 'mouseout' – Triggers the Mouseout event when the mouse leaves from an element.
    7. 'MouseMove' – Triggers the MouseMove event when the mouse moves on an element but does not leave.
Keyboard Events
    1. 'keypress' – The event is triggered when the button is pressed.
    2. 'KeyDown' – The event is triggered when the key is pressed and before the KeyPress event.
    3. 'keyup' – Triggers the event when the key is released, after the KeyDown and KeyPress events.
Form Events
    1. 'Select' – The Text field (input, textarea, etc.) is selected to trigger the event.
    2. 'change ' – Triggers the event when the control loses input focus (or when the value is changed).
    3. 'submit' – The event is triggered when the form is submitted.
    4. 'reset' – This event is triggered when the form is reset.
    5. 'focus' – triggers the event when the element receives focus, usually from a mouse device or tab navigation.
    6. 'Blur' – Triggers the event when the element loses focus, usually from a mouse device or tab navigation.
Other Events
    1. 'load' – This event is triggered when the page has finished loading (including content, picture, frame, object).
    2. 'Resize' – This event is triggered when the page size changes (such as browser scaling).
    3. 'scroll' – This event is triggered when the page scrolls.
    4. 'unload' – Triggers the event when all content is deleted from the page or frame (for example, leaving a page).

JavaScript---JavaScript and dom

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.