Ajax basics-Chapter 2)

Source: Internet
Author: User

Dom node:

DOM nodes have the following attributes:

  • nodeNameThe name of the report node (see below ).
  • nodeValueProvide the "value" of the node (see the following description ).
  • parentNodeReturns the parent node of the node. Remember, each element, attribute, and text has a parent node.
  • childNodesIs the child node list of nodes. For HTML, this list only makes sense to elements, and neither the text node nor the attribute node has children.
  • firstChildOnlychildNodesThe shortcut of the first node in the list.
  • lastChildIs another shortcut, indicatingchildNodesThe last node in the list.
  • previousSiblingBack to current nodeBefore. In other words, it returnschildNodesThe node located before the node in the list (if confused, re-read the previous sentence ).
  • nextSiblingSimilarpreviousSiblingAttribute, returnschildNodesThe next node in the list.
  • attributesUsed only for element nodes. The attribute list of the element is returned.

Next, let's take a look at the methods available for all nodes (like the node attributes, I omitted a few methods that actually do not apply to most HTML Dom operations ):

  • insertBefore(newChild, referenceNode)SetnewChildInsert nodereferenceNodeBefore. RemembernewChildThe target parent node.
  • replaceChild(newChild, oldChild)UsenewChildNode replacementoldChildNode.
  • removeChild(oldChild)Delete from the node that runs this methodoldChildNode.
  • appendChild(newChild)SetnewChildAdd to the node that runs the function.newChildAdded to the Child list of the target nodeEnd.
  • hasChildNodes()If the node that calls this method has children, true is returned; otherwise, false is returned.
  • hasAttributes()If the node that calls this method has an attribute, true is returned; otherwise, false is returned.

Most Web applications only use four node types:

  • Document NodeIndicates the entire HTML document.
  • Element NodeHTML elements, suchaOrimg.
  • Attribute nodeIndicates the attributes of HTML elements, suchhref(aElement) orsrc(imgElement ).
  • Text NodeThe text in the HTML document, such as "click on the link below for a complete set list ". This appears inp,aOrh2Text in these elements.

Basically, the first node type used in all Dom-based code is the document node.Document NodeIn fact, it is not an element in an HTML (or XML) page, but the page itself. Therefore, on the HTML web page, the document node is the entire DOM tree. Keywords can be used in JavaScript.documentAccess document node:

// And then the <HTML> element for that DOM tree
VaR mydocument = Document;
VaR htmlelement = mydocument.doc umentelement;

AvailabledocumentObject To create a new node, as shown below:

  • createElement(elementName)Creates an element with the given name.
  • createTextNode(text)Create a new text node using the provided text.
  • createAttribute(attributeName)Create a new property with the provided name.

The key here is that these methods create nodes, but they are not appended or inserted into a specific document. Therefore, you must use the method described above, as shown ininsertBefore()OrappendChild()To complete this step. Therefore, you can use the following code to create a new element and add it to the document:

var pElement = myDocument.createElement("p");var text = myDocument.createTextNode("Here's some text in a p element.");pElement.appendChild(text);bodyElement.appendChild(pElement);

Element Node:

The element has only two sets of proprietary methods:

  1. Methods related to attribute Processing:

    • getAttribute(name)The returned name isname.
    • removeAttribute(name)Delete namename.
    • setAttribute(name, value)CreatenameAnd set its valuevalue.
    • getAttributeNode(name)The returned name isname.
    • removeAttributeNode(node)Deletes attribute nodes that match the specified node.
  2. Methods related to finding nested Elements:
    • getElementsByTagName(elementName)Returns the list of element nodes with the specified name.

Processing attributes:

var imgElement = document.createElement("img");imgElement.setAttribute("src", "http://www.headfirstlabs.com/Images/hraj_cover-150.jpg");imgElement.setAttribute("width", "130");imgElement.setAttribute("height", "150");bodyElement.appendChild(imgElement);
Search for nested Elements:

// Remove all the top-level elements in the body
If (bodyelement. haschildnodes ()){
For (I = 0; I <bodyelement. childnodes. length; I ++ ){
VaR currentnode = bodyelement. childnodes [I];
If (currentnode. nodename. tolowercase () = "IMG "){
Bodyelement. removechild (currentnode );
}
}
}

You can also usegetElementsByTagName()Complete similar functions:

// Remove all the top-level elements in the body
VaR imgelements = bodyelement. getelementsbytagname ("IMG ");
For (I = 0; I VaR imgelement = imgelements. item [I];
Bodyelement. removechild (imgelement );
}
Attribute node:

  • getAttribute(name)The returned name isname.
  • removeAttribute(name)Delete namename.
  • setAttribute(name, value)CreatenameAnd set its valuevalue.

    Text Node:

    var pElements = bodyElement.getElementsByTagName("p");for (i=0; i<pElements.length; i++) {  var pElement = pElements.item(i);  var text = pElement.firstChild.nodeValue;  alert(text);}

    Note: In JavaScript, we generally need to do this to obtain the title tag and text.
    VaR Title = Dom. getelementsbytagname ("title ");
    Alert (title [0]. nodename); // obtain "title"
    When alert (title [0]. nodevalue) is used, FF can only obtain # text, while Ie can only obtain null.
    Later, I checked a lot of information. The object text type or object element is also a node.
    In the above example, the title is not a simple text content, but a text node.
    It also has its own nodename, so it should be written:
    Alert (title [0]. firstchild. nodevalue); // obtain the "title"

     

    A few other methods are specifically used for text nodes. These methods are used to add or break down data in a node:

    • appendData(text)Append the provided text to the existing content of the text node.
    • insertData(position, text)Data can be inserted between text nodes. Insert the provided text at the specified position.
    • replaceData(position, length, text)Delete characters of the specified length from the specified position, and replace the deleted text with the provided text.

    What node type?

    Most of the code we have seen so far assumes that we already know the type of nodes to be processed, but this is not always the case. For example, if you navigate to the DOM tree and process common node types, you may not know whether you have encountered elements or text. You may have obtainedpAll the children of the element, but cannot be sure to process the text,bElement orimgElement. In this case, you need to determine the type of nodes before further processing.

    Fortunately, it is easy to do. Dom node types define constants, such:

    1. Node.ELEMENT_NODEIs a constant of the element node type.
    2. Node.ATTRIBUTE_NODEIs a constant of the attribute node type.
    3. Node.TEXT_NODEIs a constant of the text node type.
    4. Node.DOCUMENT_NODEIs a constant of the document node type.

    There are other node types, but HTML is rarely used in addition to these four types. I intentionally did not give the values of these constants. Although these values are defined in the DOM specification, never use those values directly, because this is the purpose of constants!

    Nodetype attributes

    AvailablenodeTypeProperty Comparison node and the above constant -- this property is defined on the DOM node type and can be used for all nodes, as shown below:

    var someNode = document.documentElement.firstChild;if (someNode.nodeType == Node.ELEMENT_NODE) {  alert("We've found an element node named " + someNode.nodeName);} else if (someNode.nodeType == Node.TEXT_NODE) {  alert("It's a text node; the text is " + someNode.nodeValue);} else if (someNode.nodeType == Node.ATTRIBUTE_NODE) {  alert("It's an attribute named " + someNode.nodeName                         + " with a value of '" + someNode.nodeValue + "'");}
  • 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.