JavaScript DOM Operations and extensions

Source: Internet
Author: User
Tags processing instruction tag name

What is Dom???

The DOM (Document Object model) is an API (application programming Interface) for HTML and XML documents.

Note that all DOM objects in IE are implemented in the form of COM (Component Object model) objects. Dom objects in IE are not consistent with the behavior or activity characteristics of native JavaScript objects.

COM objects are executable binaries that are written in accordance with COM specifications, published in WIN32 dynamic-link libraries (DLLs), or executables (EXE), and are capable of meeting all requirements for the component architecture. The DOM defines a node interface, which is implemented as a node type in JavaScript, and all DOM objects in the Ie8-browser are implemented as COM objects. Therefore, the Ie8-browser does not support the notation of the node object.

1. Node hierarchy

First of all, we know that "in the Java World, everything is the object", as well, Js is also. However, JavaScript does not have the basic architecture of classes and interfaces supported by traditional object-oriented languages. The DOM depicts a hierarchical tree of nodes that allows developers to add, remove, and modify portions of a page.

The DOM can portray any HTML or XML document as a structure composed of multiple nodes. The nodes are divided into several different types, each representing different information and/or tags in the document. Each node has its own characteristics, data, and methods, and there is a relationship with other nodes. The relationships between nodes form a hierarchy, and all page markers appear as a tree structure with a specific node as the root node.

Take HTML as an example:

The document node is the root node of each document. In this example, the document node has only one child node, the

The document element is the most outer element of the document, and all other elements in the document are contained within the document element. There can be only one document element per document. In an HTML page, the document element is always the

Each piece of markup can be represented by a node in the tree: The HTML element is represented by an element node, the attribute is represented by an attribute node, the document type is represented by a document type node, and the comment is represented by an annotation node.

Each box is a node of the document, which represents a nodes object. The root document node of the tree, which represents the entire documentation.

2. Node type

Element node Node.element_node (1)

Attribute node Node.attribute_node (2)

Text node Node.text_node (3)

CDATA node Node.cdata_section_node (4)

Entity reference name node Node.entry_reference_node (5)

Entity name Node Node.entity_node (6)

Processing instruction Node Node.processing_instruction_node (7)

Note Node Node.comment_node (8)

Document node Node.document_node (9)

Document Type node Node.document_type_node (10)

Document fragment node Node.document_fragment_node (11)

DTD Declaration node Node.notation_node (12)

Document

Document represents the documents, in the browser, the paper object is an instance of HTMLDocument, representing the entire page, which is also a property of the Window object. Document has the following features:

(1) NodeType is 9

(2) NodeName for #document

(3) NodeValue is null

(4) ParentNode is null

(5) A child node may be a DocumentType or element

Element

element provides access to tag names, child nodes, and attributes, and the tags that we use for HTML elements such as Div,span,a are one of the elements.

Element has several features:

(1) NodeType is 1

(2) NodeName is the element tag name, TagName is also the return label signature

(3) NodeValue is null

(4) ParentNode may be document or element

(5) Child nodes may be element,text,comment,processing_instruction,cdatasection or EntityReference

Text

Text represents a textual node that contains plain text content and cannot contain HTML code, but can contain escaped HTML code. Text has the following characteristics:

(1) NodeType is 3

(2) NodeName for #text

(3) NodeValue for text content

(4) ParentNode is an element

(5) No child nodes

Attr

The attr type represents the attribute of the element, which is the node in the attributes attribute of the element, which has the following characteristics:

(1) NodeType value is 2

(2) NodeName is the name of the attribute

(3) NodeValue is the value of the attribute

(4) ParentNode is null

Comment

Comment Represents a comment in an HTML document, and it has several characteristics:

(1) NodeType is 8

(2) NodeName for #comment

(3) Contents of NodeValue as comments

(4) ParentNode may be document or element

(5) No child nodes

DocumentFragment type

DocumentFragment is the only type in all nodes that does not have a corresponding tag, which represents a lightweight document that may be used as a temporary repository to hold nodes that might be added to the document. DocumentFragment has the following features:

(1) NodeType is 11

(2) NodeName for #document-fragment

(3) NodeValue is null

(4) ParentNode is null

Node-created createelement

CreateElement creates an element by passing in a specified tag name, and if the incoming label name is an unknown, a custom label is created, note: IE8 the following browsers do not support custom labels.

Use the following:

var div = document.createelement ("div");

Use createelement Note: Elements created through createelement are not part of an HTML document, but are created and not added to an HTML document. To call a method such as AppendChild or insertbefore, add it to the HTML document tree.

createTextNode General Ibid.

createTextNode receives a parameter, which is the text in the text node, like CreateElement, the created text node is just a separate node, and it also needs to be appendchild to add it to the HTML document tree

CloneNode

CloneNode is a copy of the node that is used to return the calling method, and it receives a Boolean parameter that indicates whether to copy the child elements, using the following:

var parent = document.getElementById ("parentelement");

var Parent2 = Parent.clonenode (TRUE);//Incoming True

Parent2.id = "Parent2";

This code copies a copy of the parent element through CloneNode, where the parameter of CloneNode is true, indicating that the child node of the parent is also copied and, if passed false, that only the parent node is replicated.

This code is very simple, mainly binding button events, the event content is to copy a parent, modify its ID, and then add to the document. Here are a few things to note:

(1) Like createelement, the node created by CloneNode is simply a node that is free of HTML documents, and calls the AppendChild method to be added to the document tree

(2) If the copied element has an ID, its copy will also contain the ID, because the ID is unique, so you must modify its ID after the node is copied

(3) The call to receive the BOOL parameter is best passed in, if the parameter is not passed in, different browsers will handle their default values may be different

In addition, we have a point to note: If the replicated node is bound to an event, will the copy also bind to the event? Here to discuss the situation: (1) If the binding event is done through AddEventListener or such as the onclick, the replica node will not bind the event (2) if it is inline bound such as <div onclick= "showparent ()" > </div> if so, the replica node will also trigger the event.

Createdocumentfragment

The Createdocumentfragment method is used to create a documentfragment. The aforementioned documentfragment represents a lightweight document that is primarily intended to store temporary nodes that are ready to be added to the document.


This code binds the button to an event that creates 100 Li nodes and then adds them to the HTML document in turn. This has a drawback: each time a new element is created and then added to the document tree, this process causes the browser to reflow. The so-called reflow simply means that the element size and position are recalculated, and if too many elements are added, it can cause performance problems. This time, is to make the createdocumentfragment. Summary of Creation Type

The creation API mainly includes createelement, createTextNode, CloneNode, and createdocumentfragment four methods, the following points need to be noted:

(1) The node they create is an isolated node that is added to the document via AppendChild.

(2) CloneNode to note if the replicated node contains child nodes and event bindings.

(3) using Createdocumentfragment to resolve performance issues when adding a large number of nodes

Modified Type

The API to modify page content includes: Appendchild,insertbefore,removechild,replacechild.

AppendChild

AppendChild we have used many times before, that is, adding the specified node to the end of the child element of the node that called the method. The method of invocation is as follows: Parent.appendchild (child); The Children node will be the last sub-node of the parent node This method is simple, but one thing to note: If the added node is a node that exists on a page, After execution, the node is added to the specified location, and the node is removed from its original location, meaning that there will not be two nodes on the page, which is equivalent to moving the node to another place.


This code is mainly to get the child node on the page, and then add to the specified location, you can see the original child node is moved to the parent. Here's another point to note: If a child is bound to an event and is moved, it is still bound to the event. InsertBefore

InsertBefore used to add a node to a reference node, use the following:

Parentnode.insertbefore (Newnode,refnode);

ParentNode represents the parent node after the new node is added

NewNode represents the node to be added

Refnode represents the reference node, before the new node is added to the node

There are a few points to note about the second parameter reference node:

(1) Refnode is a must pass, if not pass the parameter will be an error

(2) If refnode is undefined or null, InsertBefore will add the node to the end of the child element

RemoveChild

RemoveChild, as the name implies, is to delete the specified child node and return it, using the following:

var deletedchild = parent.removechild (node);

Deletedchild points to the deleted node's reference, which equals node, the deleted node still exists in memory and can be used for next steps.

Note: If the deleted node is not its child node, the program will error. We can make sure that we can delete it in the following way:

if (Node.parentnode) {

Node.parentNode.removeChild (node);

}

Gets the parent node of the node itself through the node, and then deletes itself.

ReplaceChild

ReplaceChild is used to replace another node with one node, using the following: Parent.replacechild (Newchild,oldchild);

Newchild is a replacement node, either a new node or a node on a page, or a node on a page that is moved to a new location, and Oldchild is the node that is replaced.

Page Modification API is mainly these four interfaces, to pay attention to a few features:

(1) Whether it is a new or replacement node, if the new or replaced node is originally present on the page, then the node of its original position will be removed, that is, the same node cannot exist in multiple locations on the page

(2) Events bound by the node itself will not disappear and will remain.

Node Query type Apidocument.getelementbyid

This interface is simple, returns an element based on the element ID, the return value is an element type, and returns null if the element does not exist. There are a few things to note about using this interface:

(1) The ID of the element is case sensitive, be sure to write the ID of the element

(2) There may be multiple elements with the same ID in the HTML document, the first element is returned

(3) Search elements only from the document, if an element is created and an ID is specified but not added to the document, the element will not be found.

document.getElementsByTagName

This interface gets the element according to the element tag name, returns an immediate htmlcollection type, what is the instant htmlcollection type?

There are a few things to note about this approach:

(1) If you want to cycle through the Htmlcollection collection, it is best to cache its length, because each cycle will calculate the length, and temporarily cache it to improve efficiency.

(2) If the specified label is not present, the interface returns not NULL, but an empty htmlcollection

(3) "*" means all labels


One button is to display the number of htmlcollection elements, and the other button can add a div tag to the document. The Htmlcollcetion element mentioned earlier indicates that the collection is changed at any time, that is, there are several div in the document, it will change at any time, when we add a div and then visit htmlcollection, we will include this new Div. Document.getelementsbyname

Getelementsbyname is primarily obtained by specifying the Name property, which returns an immediate NodeList object. The main points to note when using this interface are:

(1) The return object is an instant nodelist, which is changeable at any time

(2) In HTML elements, not all elements have a name attribute, such as a DIV does not have a Name property, but if you force the Name property of the Div, it can be found.

(3) in IE, if the ID is set to a value, and then passed in the Getelementsbyname parameter value and the ID value, then this element will be found, so it is best not to set the same value to the ID and name

Extension one. Selector Api1.queryselector () method

The method receives a CSS selector, returns the first element that matches the pattern, and returns null if no matching element is found.

When the Queryselector () method is called through the document type, a matching element is found within the scope of the documentation element. When the Queryselector () method is called through the element type, only the matching elements are found in the range of the descendant elements of the elements.

Note: one of the most common features in many JavaScript libraries is to select DOM elements that match a pattern based on CSS selectors. In fact, the core of jquery is querying DOM documents with CSS selectors to get references to elements, thus throwing away getElementById () and Getelementbytagname ().

CSS selectors can be simple or complex, depending on the situation. If an unsupported selector is passed in, Queryselector () throws an error.

2.querySelectorAll ()

The Queryselectorall () method accepts a parameter like the Queryselector () method, which is a CSS selector, but returns not only an element but an instance of the nodelist.

As with Queryslector () the Queryslectorall () method can be adjusted with document,element,documentfragment.

To get each element of the returned nodelist, you can use the item () method, or you can use the square bracket syntax, for example:

Getelementsbyclassname ()

1) How to use: Element.getelementsbyclassname ("Classnames"), where element is a valid DOM element (including document)

Classnames is a combination of CSS class names (spaces between multiple class names, which can be separated by multiple spaces), such as

Element.getelementsbyclassname ("Class2 Class1")

Elements that have both the Class1 and Class2 styles applied in the elements descendant element (style name is not distinguished in order) are selected 2) Description: A. The return value is a nodelist set (distinct from the definition and concept of array)

B. The method can only select the descendant elements of the element that called the method.

3) Compatibility: IE8 and the following versions of browsers do not implement the Getelementsbyclassname method

HTML5 adds the Getelementsbyclassname () method, which can be called from the Document object and all HTML elements

Event

An event is a specific interaction moment that occurs in a document or browser window

I. Flow of events

On the page, when you click an element, you also click its containing container. An event flow is a description of the order in which events are received from the page. IE is an event bubbling stream, and Netscape is the event capture stream.

Event bubbling

When an event starts, it is received by the most specific element (the deepest nested node in the document) and then propagated up to the less specific node (document); (All modern browsers support event bubbling) If you click the <div> element in the page, The Click event is then propagated in the following order:

(1) <div>

(2) <body>

(3)

(4) Document

Event capture

A less specific node is the first to receive an event, and the most specific node receives the event at the end. (Older browsers do not support) if you click the <div> element in the page, the click event propagates in the following order:

(1) Document

(2)

(3) <body>

(4) <div>

Second, DOM event flow

The event flow specified in the DOM2 level event consists of three phases:

1. Event Capture Phase

2. In the target stage

3. Event bubbling Phase

In the DOM event stream, the actual target (div element) does not accept events during the capture phase. This means that during the capture phase, events are stopped from document to

Most browsers that support DOM event streams implement a specific behavior: even though the DOM2 level event specification explicitly requires that the capture phase not involve event targets, IE9, Safari, Chrome, Firefox and Opera9.5 and later will trigger events on event objects during the capture phase. As a result, there are two opportunities to manipulate events above the target object.

Browser's kernel

It is divided into two main parts: the rendering engine (layout engineer or rendering engine) and the JS engine. Rendering Engine: Responsible for obtaining the content of the Web page (HTML, XML, images, etc.), organizing the message (such as adding CSS, etc.), and calculating how the Web page is displayed, and then outputting it to the monitor or printer. The browser's kernel is different from the syntax of the Web page, so the effect of rendering is not the same. The kernel is required for all Web browsers, e-mail clients, and other applications that need to edit and display Web content. JS Engine: Parsing and executing JavaScript to achieve the dynamic effect of Web pages. The first rendering engine and the JS engine are not clearly distinguished, and then the JS engine becomes more independent, the kernel tends to refer only to the rendering engine.

Parse HTML to build the DOM tree, build the render tree, layout render tree, draw a render tree.

When the browser obtains an HTML file, it loads "top-down" and parses the render during the loading process.

Analytical:

1. The browser parses the HTML into a DOM tree, and the construction of the DOM tree is a deep traversal process: All the child nodes of the current node are built before the next sibling node of the current node is built.

2. Parse the CSS into CSS Rule Tree.

3. Construct Rendering tree based on dom trees and Cssom.

Note: The Rendering tree is not the same as the DOM tree, because something like a Header or display:none doesn't have to be placed in the render tree.

4. With the render Tree, the browser can already know which nodes are in the Web page, the CSS definitions for each node, and their dependencies. The next step, called Layout, is to calculate the position of each node in the screen as the name implies.

5. The next step is to draw, which is to traverse the render tree and draw each node using the UI back-end layer.

The process is gradual, and for a better user experience, the rendering engine will render the content to the screen as early as possible, and will not wait until all the HTML is resolved before building and laying out the render tree. It shows part of the content as part of parsing, and may also be downloading the rest of the content over the network.

(1) Reflow (reflow): The browser takes time to render, and when it finds that a part has changed and affects the layout, it needs to go back and render again.

(2) Repaint (redraw): If you just change the background color of an element, text color, etc., does not affect the elements around or the internal layout of the properties, will only cause the browser Repaint, redraw a part.

Reflow takes more time than repaint, and it also affects performance. So when writing code, try to avoid too much reflow.

Reasons for Reflow:

(1) When the page is initialized;

(2) when manipulating the DOM;

(3) The dimensions of some elements have changed;

(4) If the properties of the CSS have changed.

Reduce Reflow/repaint

(1) Do not modify the DOM style one by one. Instead, you might as well pre-define the CSS class and then modify the DOM's className.

(2) Do not place the attribute value of the DOM node in a loop as a variable in the loop.

(3) for animated HTML components using fixed or absoult position, then modifying their CSS is not reflow.

(4) Never use table layout. Because a small minor change can cause the entire table to be re-laid.

You should note that when you write CSS:

CSS selectors are matched from right to left. Right to left, so, #nav Li we think this is a very simple rule, seconds can match to the desired element, but, however, is from right to left to match ah, so, will go to find all Li, and then to determine whether its parent element is #nav. , therefore, you need to note when writing CSS:

(1) Dom depth is as shallow as possible.

(2) Reduce the number of inline JavaScript, CSS.

(3) Use modern and legitimate CSS properties.

(4) Do not specify the class name or label for the ID selector, because the ID can uniquely determine an element.

(5) Avoid descendant selectors and use sub-selectors as much as possible.

Cause: The probability of a child-element match is greater than the descendant-element-match character. Descendant selector, #tp p{} sub-selector: #tp >p{}

(6) Avoid using wildcard characters, for example:

. mod. HD *{font-size:14px;}

Based on the matching order, the wildcard character is first matched, that is, the wildcard is matched first and then matched. HD (that is, to traverse all the nodes on the DOM tree for his parent element), and then match the. MoD, which can be imagined.

csdn:http://blog.csdn.net/qq_33430445/article/details/76977623

JavaScript DOM Operations and extensions

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.