Home  >  Article  >  Web Front-end  >  JavaScript advanced programming DOM study notes_javascript skills

JavaScript advanced programming DOM study notes_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:02:25984browse

Chapter 10 DOM
DOM is an API for XML and HTML documents: it specifies the attributes and methods for text node manipulation, and the specific implementation is implemented by the respective browsers.
1. Node hierarchy
1) Document node: document, the root node of each document.
2) Document element: The element is the outermost element of the document and the first child node of the document node.
3) Node type:
①Node is the base type of various node types in the DOM, sharing the same basic properties and methods.
□ 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);
The nodeType attribute of each node returns one of the above types, which is a constant .
The node type can be obtained by comparing the nodeType attribute with the numeric value.
②nodeName and nodeVlue attributes.
③The child node information of each node is stored in the childNodes attribute, and a NodeList object is stored in the childNodes attribute.
□ NodeList object, an array-like object, has a length attribute, but is not an instance of Array.
□ To access the nodes in the NodeList, you can use square brackets or use the item() method.
var firstChild = someNode.ChildNodes[0];
var secondChild = someNode.ChildNodes.item(1);
var count = someNode.childNodes.length;
□ Convert NodeList to array object .
function convertToArray(nodes){
var array = null;
try{
array = Array.prototype.slice.call(nodes,0); //Non-IE
}catch( ex){
array = new Array();
for(var i = 0,len = nodes.length; i array.push(nodes[i]);
}
}
return array;
}
④parentName attribute: points to the parent node in the document tree.
⑤previousSibling attribute and nextSibling attribute: previous/next sibling node.
⑥firstChild attribute and lastChild attribute: previous/next child node.
⑦hasChildNodes() method: Returns true if it contains child nodes, otherwise it returns false.
⑧appendChild() method: Add a child node to the end of the childNodes list and return the newly added node.
⑨insertBefore() method: two parameters: the node to be inserted and the node used as a reference. Return the newly added node.
⑩replaceChild() method: two parameters: the node to be inserted and the node to be replaced. Return the newly added node.
⑾removeChild() method: remove node.
⑿cloneNode() method: accepts a Boolean value. true means deep copy, copying nodes and sub-nodes. false means shallow copy, only copying the own node.
⒀nomalize() method: Process text nodes in the document tree.
4) Document type (for document objects)
①Document type represents a document, which is an instance of the HTMLDocument type and represents the entire HTML page. The document object is a property of the window object and can be accessed as a global object.
②documentElement attribute; this attribute always points to the element in the HTML page.
③body attribute; points directly to the

element.
④doctype attribute: Access , which is supported by different browsers. Of limited use.
⑤title attribute: The text of the title can be obtained and set.
⑥URL attribute: URL in the address bar.
⑦domain attribute: The domain name of the page (can be set, with restrictions)
⑧referrer attribute: Save the URL of the page linked to the current page
⑨getElementById() method: Pass in the ID of the element and return the element node.
⑩getElementsByTagName() method: Pass in the element name and return NodeList.
□ Returns an HTMLCollection object in HTML, similar to NodeList.
□ Access the HTMLCollection object: square bracket syntax, item() method, namedItem() method. The HTMLCollection object can also obtain the items in the collection through the name attribute of the element.
⑾getElementsByName() method: Returns all elements with the given name attribute.
⑿Special collections, these collections are HTMLCollection objects.
□ document.anchors: Contains all elements with the name attribute in the document.
□ document.applets: Contains all elements in the document.
□ document.forms: Contains all
elements in the document.
□ document.images: Contains all JavaScript advanced programming DOM study notes_javascript skills elements in the document.
□ document.links: Contains all elements with href attributes in the document.
⒀DOM consistency detection: The document.implementation attribute provides objects with corresponding information and functions.
□ This object has one method: hasFeature(): two parameters: the name and version number of the DOM feature to be detected.
□ Functions: Core, XML, HTML, Views, StyleSheets, CSS, CSS2, Events, UIEvents, MouseEvents, MutationEvents, HTMLEvents, Range, Traversal, LS, LS-Async, Validation
⒁Write the output stream Web pages: write(), writeln(), open() and close().
5) Element type
① is used to represent XML or HTML elements, providing access to element tag names, sub-nodes and attributes.
②The nodeName attribute or tagName attribute can be used to access the element tag name. tagName will return the uppercase tag name in HTML and unchanged in XML.
(1) HTML element
■All HTML elements are represented by the HTMLElement type, a subclass of the Element type, with the following attributes:
□id: The unique identifier of the element in the document.
□title: Additional explanatory information about the element, usually displayed through a tool tip bar.
□lang: The language code of the element content, rarely used.
□dir: The direction of the language, the value is "ltr" or "rtl", rarely used.
□className: Corresponds to the class attribute of the element, which is the css class specified for the element.
The above attributes can be used to obtain or modify the corresponding characteristic values.
(2) Get attributes
①getAttribute() method: You can get the values ​​of recognized attributes and custom attributes.
□All properties of any element can also be accessed through the attributes of the DOM element itself. alert(div.id);alert(div.align);
□Only recognized (non-custom) features will be added to the DOM object in the form of attributes.
□The style attribute accesses the attribute value CSS text through getAttribute(). An object is accessed through properties.
□onclick attribute: getAttribute(), returns a JS code string. Returns a function via property access.
□Generally, attributes are obtained through attributes. Only when obtaining custom attribute values, use getAttribute().
(3) Set attributes
①setAttribute(): two parameters, the name and value of the attribute to be set. If the attribute already exists, setAttribute() will replace the existing value with the specified value; if the attribute does not exist, setAttribute() will create the attribute and set the corresponding value.
□This method can operate both HTML attributes and custom attributes.
□All recognized characteristics are attributes, so assigning values ​​to attributes directly can set the value of the attribute.
□In IE6 and IE7, if setAttribute() sets class and style, the event handler will have no effect. But setting characteristics through properties is not recommended.
②removeAttribute(): completely remove the attribute of the element (not supported by IE6).
(4) attributes attribute
① This attribute contains a NameNodeMap object (a "dynamic" collection similar to NodeList). Each attribute of the element is represented by an Attr node, and each node is stored in the NameNodeMap object.
□getNameItem(name): Returns the node whose nodeName attribute is equal to name
□removeNameItem(name): Removes the node whose nodeName attribute is equal to name from the list.
□setNameItem(node): Add a node to the list, using the nodeName attribute of the node as the index.
□item(pos): Returns the node located at the digital pos position.
(5) Create elements
① Use the document.createElement() method to create new elements. Parameters: tag name.
② createElement() in IE can pass in complete element tags to prevent problems in IE7 and IE6:
□ cannot set the name attribute of dynamically created ");
}
(6) element The child node
① The childNode attribute of the element contains all its child nodes: elements, text nodes, comments or processing instructions.
□General browsers will parse the whitespace characters in the element node space into text nodes when parsing childNodes, but IE will not. Therefore, the traversal execution operation requires checking the nodeType attribute.
For(var i= 0, len = element.childNode.length; i> len; i ){
If(element.childNodes[i].nodeType == 1){
//Execute something Some operations
}
}
□Element nodes support the getElementByTagName() method.
6) Text type
①Text nodes are represented by the Text type and contain plain text content without HTML code.
□Does not support (no) child nodes
□The nodeValue attribute and the data attribute can access the text contained in the Text node.
②Operation text node
□appendData(text): Add text to the end of the node.
□deleteData(offset,count): Delete count characters starting from the offset position.
□insertData(offset,text): Insert text at offset position;
□replaceData(offset,count,text): Use text to replace the string starting from the position specified by offset to offset count.
□splitText(offset): Split the current text node into two text nodes from the position specified by offset.
□substringData(offset,count): Extract the string starting from the position specified by offset and ending at offset count.
□Text nodes have a length attribute that saves the number of characters in the node. The same values ​​are also stored in nodeValue.length and data.length.
○When modifying the text node value, the string is HTML encoded and special symbols are escaped:
div.firstChild.nodeValue = "Someother"; //Output Someother strong> >
③Create text node
□Use document.createTextNode() to create a new text node. Parameters: Text to be inserted (automatically encoded in HTML or XML format)
④Normalized text nodes
□DOM operations can insert multiple text nodes into the same parent element, but it will cause confusion.
□The normalize() method inherited through the node type can merge all text nodes on the same parent element.
⑤Split text node
□Text type method splitText(): Contrary to the node method normalize(), pass in a position parameter, split it into two text nodes from the position, and return the following text node.
□Splitting text nodes is a common DOM parsing technique to extract data from text nodes.
7) Comment type
□Comment type inherits from the same base class as Text type, so it has all string operation methods except splitText().
□Comment nodes can be created using document.createComment().
8) CDATASection type
□CDATASection type only represents the CDATA area for XML-based documents.
□CDATASection type inherits from Text type and has all methods except splitText().
□All major browsers cannot correctly parse this type.
9) DocumentType type
□IE does not support
□DocumentType objects cannot be dynamically created in DOM level 1.
□DocumentType object is saved in document.doctype.
◇name attribute: document type name.
◇entities attribute: NamedNodeMap object of the entity described by the document type.
◇notation attribute: NamedNodeMap object of the symbol described by the document type.
10) DocumentFragment type
□DOM stipulates that a document fragment is a "lightweight" document that can contain and control nodes, but does not occupy additional resources like a complete document.
□Document fragments cannot be added to the document, only document fragments will be added as nodes saved in the "warehouse".
var fragment = document.createDomFragment();
var ul = document.getElementById("myList");
var li = null;
for(var i= 0; ili = document.createElement("li");
li.appendChild(document.createTextNode("haha"));
fragment.appendChild(li);
}
ul.appendChild.appendChild(li);
□ You can add the content of the document fragment to the document through appendChild() or insertBefore().
11) Attr type
□ is a node, but attributes are not considered part of the DOM document tree. Such nodes are rarely used.
□Attr object has 3 attributes:
◇name attribute: attribute name (such as nodeName)
◇value attribute: attribute value (such as nodeValue)
◇specified attribute: Boolean value, used to distinguish Whether the attribute is specified in code or is default.
□ It is not recommended to access feature nodes directly. It is recommended to use getAttribute()
setAttribute() and removeAttribute() methods. 0

2. DOM extension
1. Presentation mode
①The compatMode attribute of the document object
□The value is "CSS1Compat", which is the standard mode.
□The value is "BackCompact", which is mixed mode.
②IE8 introduces a new attribute documentMode for document objects, returning values: 5 (mixed mode), 7 (simulation mode), 8 (standard mode)
2. Scrolling
□Scrolling methods are all of HTMLElement type The extension exists and can be used on element nodes.
□scrollIntoView(bool): Scroll the browser window or container element so that the element is visible in the viewport. (If the parameter is true or omitted, scroll to the top).
□scrollIntoViewIfNeeded(bool): Only scroll the browser window or container element to make the current element visible if the current element is not visible in the viewport. (Safari and Chrome implementation).
□scrollByLines(lineCount): Scroll the content of the element by the specified number of lines. lineCount can be a positive/negative number. (Available in Safari and Chrome)
3. children attribute
□The children attribute only contains those nodes that are also elements among the child nodes of the element.
□As an HTMLCollection object.
□Firefox does not support it. The children collection in IE will contain comment nodes.
4. The contains() method
□ should be called on the ancestor node as the starting point of the search, passing in the node to be detected as a parameter. Return true to pass in the node as a descendant of the current node.
□Firefox does not support the contains() method, and implements the alternative compareDocumentPosition() method at the DOM3 level to determine the relationship between two nodes. Safari versions below 2.x are not supported.
Compatible with various browser codes:
function contains(refNode, otherNode){
if(typeof refNode.contains == "function" && (!client.engine.webkit || client.engin.webkit > =552)){
return refNode.contains(otherNode);
}else if(tyepof refNode.compareDocumentPosition == "function"){
return !!(refNode.compareDocumentPosition(otherNode)&16);
}else{
var node = otherNode.parentNode;
do{
if(node ​​=== refNode){
Return true;
}else{
node = node.parentNode;
}
}while(node ​​!== null);
return false;
}
}
5. Operation content
①innerText attribute
□Can read all texts in the node document book from shallow to deep.
□ Setting the node text through the inner.Text property will remove all previously existing child nodes and completely change the DOM tree.
□Text assigned to this attribute will be automatically HTML encoded.
□Firefox does not support innerText, but supports the textContent attribute with a similar function.
□innerText: supports IE, Safari, Opera, Chrome
□textContent: supports Safari, Firefox, Opera, Chrome
Compatible code:
function getInnerText(element){
return (typeof element .textContent == "string")?element.textContent:element.innerText;
}

function setInnerText(element, text){
if(typeof element.textContent == "string") {
element.textContent = text;
}else{
element.innerText = text;
}
}
②innerHTML attribute
□When reading information, return the current element HTML representation of all child nodes.
□When writing information, a new DOM subtree will be created according to the specified value, and all child nodes of the current element will be replaced with this subtree.
□innerHTML limitation: Inserting <script> elements will not be executed. Inserting <style> has a similar problem. <BR>□ Not all elements have the innerHTML attribute. Unsupported elements are <col>, <colgroup>, <frameset>, <head>, <html>, <style>, <table>, <tbody>, <thead>, <tfoot>, <title> and <tr>. <BR>③outerText attribute <BR>□Basically the same as innerText, the difference is that when writing information, the containing node will be replaced. <BR>□Firefox does not support it. <BR>□Not recommended. <BR>④outerHTML attribute <BR>□ is basically the same as innerHTML. The difference is that when writing information, the containing node will be replaced. <BR>□Firefox does not support <BR>□Not recommended <BR>⑤Memory and performance issues <BR>□ innerText, innerHTML, outerText, outerHTML replacement of child nodes may cause memory problems in the browser. Event handlers set by elements in the deleted subtree or properties with values ​​of JS objects still exist in memory. <BR>□ When inserting a large amount of new HTML, it is much more efficient to use HTML than to go through multiple DOM operations. <BR>3. DOM operation technology<BR>1. Dynamic script<BR>①Insert external files: <BR>function loadScript(url){ <BR>var script = document.createElement("script"); <BR> script.type = "text/javascript"; <BR>script.src = url; <BR>document.body.appendChild(script); <BR>} <BR>②Specify JavaScript code method<BR>□IE Lieutenant General <script> is treated as a special element and does not allow DOM access to its child nodes. <BR>Compatible method: <BR>function loadScriptString(code){ <BR>var script = document.createElement("script"); <BR>script.type = "text/javascript"; <BR>try{ <BR>script.appendChild(document.createTextNode(code)); <BR>}catch(ex){ <BR>script.text = code; <BR>} <BR>document.body.appendChild(script); <BR> } <BR>2. Dynamic style<BR>①External link<BR>function loadStyles(url){ <BR>var link = document.createElement("link"); <BR>link.rel = "stylesheet"; <BR>link.href = url; <BR>var head = document.getElementsByTagName("head")[0]; <BR>head.appendChild(link); <BR>} <BR>②Use the <style> element to Contains embedded CSS <BR>□IE treats <style> as a special node similar to <script> and does not allow access to its child nodes. <BR>□ Reusing a <style> element and setting its styleSheet.cssText attribute again may cause the browser to crash. <BR>fucnction loadStyleString(css){ <BR>var style = document.createElement("style"); <BR>style.type = "text/css"; <BR>try{ <BR>style.appendChild(document .createTextNode(css)); <BR>}catch(ex){ <BR>style.styleSheet.cssText = css; <BR>} <BR>var head = document.getElementsByTagName("head")[0]; <BR>head.appendChild(style); <BR>} <BR>3. Operation table <BR>① Attributes and methods added for the <table> element <BR>□caption: Saves the <caption> element (if any ) pointer; <BR>□tBodies: is an HTMLCollection of <tobdy> elements; <BR>□tFoot: holds the pointer to the <tfoot> element (if any); <BR>□tHead: holds the <thead>Pointer to the element (if any); <BR>□rows: is an HTMLCollection of all rows in a table; <BR>□createTHead(): Creates a <thead> element, puts it into the table, and returns a reference. <BR>□createCaption(): <BR>□deleteTHead(): Delete the <thead> element. <BR>□deleteTFoot(): <BR>□deleteCaption(): <BR>□deleteRow(pos): <BR>□insertRow(pos): Insert a row at the specified position in the rows collection. <BR>②The attributes and methods added to the <tbody> element are: <BR>□rows: holds the HTMLCollection of rows in the <tbody> element. <BR>□deleteRow(pos): Delete the row at the specified position; <BR>□insertRow(pos): Insert a row at the specified position in the rows collection and return the reference of the inserted row. <BR>③Attributes and methods added to the <tr> element <BR>□cells: Saves the HTMLCollection of cells in the <tr> element; <BR>□deleteCell(pos): Delete the cell at the specified position. <BR>□insertCell(pos): Insert a cell into the specified position in the cells collection and return the inserted cell reference. <BR>4. Use NodeList <BR>□NodeList and its "close relatives" NamedNodeMap (attribute attribute in Element type) and HTMLCollection. These three collections are "dynamic" and they will change whenever the document structure changes. Get updated. <BR>□ Try to reduce the number of visits to NodeList. Because every time NodeList is accessed, a document-based query will be run. Consider caching the values ​​obtained from NodeList. <br><br>Chapter 11 DOM2 and DOM3 <BR>1. DOM changes<BR>1. Changes in XML namespace<BR>①Changes in Node type<BR>■In DOM2 level, the Node type includes the following Namespace-specific properties.<BR>□localName: Node name without namespace prefix. <BR>□namespaceURI: namespace URI, null if not specified. <BR>□prefix: namespace prefix, null if not specified. <BR>■DOM level 3 <BR>□isDefaultNamespace(namespaceURI): The specified namespaceURI returns true in the case of the current default namespace. <BR>□lookupNamespaceURI(prefix): Returns the namespace of the given prefix. <BR>□lookupPrefix(namespaceURI): Returns the prefix of the given namespaceURI. <BR>②Document type changes <BR>■In DOM2 level, related to namespace <BR>□createElementNS(namespaceURI, tagName): Use the given tagName to create a new element belonging to the namespace namespaceURI. <BR>□createAttributeNS(namespaceURI, attributeName): <BR>□getElementBytagNameNS(namespaceURI, tagName): <BR>③Changes in Elment type <BR>■DOM level 2 core <BR>□getAttributeNS(namespaceURI, localName) <BR> □getAttributeNodeNS(namespaceURI, localName) <BR>□getElementsByTagNameNS(namespaceURI, localName) <BR>□hasAttributeNS(namespaceURI, localName) <BR>□removeAttributeNS(namespaceURI, localName) <BR>□setAttributeNodeNS(attrNode): Set belongs to the namespace Characteristic node of namespaceURI. <BR>④Changes in NamedNodeMap type <BR>□getNamedItemNS(namespaceURI, localName) <BR>□removeNamedItemNS(namespaceURI, localName) <BR>□setNamedItemNS(node): Add node, this node has specified namespace information in advance. <BR>2. Changes in other aspects <BR>①Changes in DocumentType type <BR>□Added 3 new attributes: publicId, systemId and internalSubset <BR>□publicId and systemId represent two information segments in the document type declaration. <BR>□internalSubset: used to access additional definitions contained in the document type declaration. <BR>②Changes in Document type <BR>□importNode() method: Get a node from one document and then import it into another document to make it part of the document structure. <BR>◇Each node has an ownerDocument attribute, indicating the document it belongs to. <BR>◇The nodes passed in to appendChild() belong to different documents, which will cause errors. <BR>◇The importNode() method is very similar to Element's cloneNode method, accepting two parameters: the node to be copied and a Boolean value indicating whether to copy the child node. Returns a copy of the original node, but available for use in the current document. <BR>□defaultView attribute: Saves a pointer to the window (or frame) that owns the given document. <BR>◇IE does not support this attribute, but there is an equivalent attribute parentWindow. <BR>◇ Determine the document ownership window compatibility code: <BR>var parentWindow = document.defaultView || document.parentWindow; <BR>□createDocuemntType(): Create a new DocumentType node, accepting three parameters: document type name, publicId, systemId. <BR>□createDocument() method: Create a new document. Three parameters: the namespaceURI of the element in the document, the tag name of the document element, and the document type of the new document. <BR>□The "DOM2-level HTML" module adds a new method to document.implementation called createHTMLDocument(). Only accepts the text in title as parameter. Returns a new HTML document. Includes <html>, <head>, <title> and <body>. <BR>③Changes in Node type <BR>□isSupported() method: similar to the hasFeature() method introduced by document.implementation in DOM1 level. Used to determine what capabilities the current node has. Two parameters: feature name and feature version number. <BR>□isSameNode() method: Pass in the node and return true if it is the same node as the reference node. <BR>□isEqualNode() method: Pass in the node and return true if it is equal to the reference node. <BR>□setUserData() method: assign data to the node. Three parameters: the key to be set, the actual data and the processing function. <BR>◇The processing function accepts 5 parameters: the value of the table operation type (1 copy 2 import 3 delete 4 rename), data key, data value, source node and target node. <BR>var div = document.createElement("div"); <BR>div.setUserData("name","Nicholas",fucntion(operation, key, value, src, dest){ <BR>if(operation = = 1){ <BR>dest.setUserData(key, value); <BR>} <BR>}); <BR>④Frame changes<BR>□Frames and inline frames are represented by HTMLFrameElement and HTMLIFrameElement respectively. <BR>□contentDocument attribute: new attribute of DOM2-level middle frame and inner frame. This property contains a pointer to the document object that represents the frame's contents. <BR>□The contentDocument attribute is a Document type instance, so you can use it like any other HTML document, including all properties and methods. <BR>□IE8 did not support the contentDocument attribute in the frame before, but supported a property called contentWindow, which returns the window object of the frame. <BR>□Access the inline frame document object compatible code: <BR>var iframe = document.getElementById("myIframe"); <BR>var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; <BR>2. Style <BR>1. Access the style of the element <BR>①style attribute <BR>□HTML elements that support the style attribute have a corresponding style attribute in JS. <BR>□This style object is an instance of cssStyleDeclaration and contains the style specified through the style attribute. <BR>□Any CSS properties specified in the style attribute will appear as corresponding properties of this style object.CSS property names using dashes must be converted to camel case before they can be accessed through js. The float attribute cannot be used directly. IE uses styleFloat to access, and other browsers use cssFloat to access. <BR>□ If the style attribute is not set for the element, the style object may contain some default values, but these values ​​do not reflect the correct style information of the element. <BR>②DOM style attributes and methods <BR>1) DOM2 level also defines some attributes and methods for the style object. Styles can also be modified when providing attribute values. <BR>□cssText: Access the css code in the style attribute. <BR>□length: The number of css attributes applied to the element. <BR>□parentRule: CSSRule object representing css information. <BR>□getPropertyCSSValue(propertyName): Returns the CSSValue object containing the given property value, including two properties cssText and cssValueType. <BR>□getProperytPriority(propertyName): If the given property uses the !important setting, return "important", otherwise return an empty string. <BR>□item(index): Returns the name of the CSS property at the given position. <BR>□removeProperyt(propertyName): Remove the given property from the style. <BR>□setProperty(propertyName, value, priority): Set the given property to the corresponding value and add the priority flag ("important" or an empty string). <BR>2) The purpose of using <BR>□ to design the length attribute is to use it in conjunction with the item() method. in order to iterate over the css properties defined in the element. <BR>□Firefox, Safari, Opera9 and higher, and chrome all support these properties and methods. IE only supports cssText. <BR>□getPropertyCSSValue() is only supported by Safari and chrome. <BR>③Computed style <BR>□ "DOM2-level style" enhances document.defaultView and provides the getComputedStyle() method. <BR>□getComputedStyle(): 2 parameters: the element to get the calculated style and a pseudo-element string (such as: after). If pseudo-element information is not required, the second parameter can be null. Returns a CSSStyleDeclaration object (same type as the style attribute). <BR>□IE does not support the getComputedStyle() method. However, elements with style attributes in IE have a currentStyle attribute (an instance of CSSStyleDeclaration) that contains all calculated styles of the current element. <BR>□ Computed style compatible code: <BR>var myDiv = document.getElementById("myDiv"); <BR>var computedStyle = document.defaultView.getComputedStyle(mydiv, null) || myDiv.currentStyle; <BR>alert (computedStyle.width); <BR>alert(computedStyle.height); <BR>2. Manipulate style sheet <BR>①CSSSStyleSheet type <BR>1) Manipulate <link> element style sheet and <style> element style sheet. <BR>2) Determine whether the browser supports DOM2-level style sheets. <BR>var supportDOM2StyleSheets = document.implementation.hasFeature("StyleSheet","2.0"); <BR>3) CSSStyleSheet inherits from StyleSheet, which can be used as a basic interface to define non-CSS style sheets. The properties inherited from the StyleSheet interface are as follows: <BR>□disabled: A Boolean value indicating whether the style sheet is disabled. Read/write. Set to true to disable. <BR>□href: The URL of the stylesheet if the stylesheet is included via <link>, otherwise null. <BR>□media: A collection of all media types supported by the current style sheet. Like all DOM collections, there is a length property and an item() method. <BR>□ownerNode: Pointer to the node that owns the current style sheet. If imported through @import, the attribute is null. IE does not support this attribute. <BR>□parentStyleSheet: When the current style sheet is imported through @import, this attribute points to the pointer to the style sheet that imported it. <BR>□title: The value of the title attribute in ownerNode. <BR>□type: A string representing the style sheet type. For CSS style sheets, this string is "type/css".<BR>■The above attributes are all read-only except disabled. <BR>4) CSSStyleSheet adds the following properties and methods based on the above: <BR>□cssRule: A collection of style rules contained in the style sheet. IE does not support it, but has a similar rules attribute. <BR>□ownerRule: If the style sheet is imported through @import, this attribute is a pointer pointing to the rule representing the import; otherwise, it is null. IE does not support this attribute. <BR>□deleRule(index): Delete the rule at the specified position in the cssRules collection. IE does not support this, but does support a similar removeRule() method. <BR>□insertRule(rule,index): Insert the rule string into the specified position in the cssRules collection. IE does not support it, but supports a similar addRule() method. <BR>5) Get the style sheet object <BR>□All style sheets applied to the document are represented by the document.styleSheets collection. The number of style sheets in the document can be obtained through the length property of this collection, and each style sheet can be accessed through square bracket syntax or the item() method. <BR>var sheet = null; <BR>for(var i = 0, len = document.styleSheets.length; i < len; i ){ < len; i ){ <BR>sheet = document.styleSheets[i]; <BR>alert( sheet.href); <BR>} <BR>□The style sheets returned by document.styleSheets of different browsers are also different. All browsers include the <style> element and the stylesheet introduced by the <link> element with the rel attribute set to "stylesheet". <BR>□ The CSSStyleSheet object can be obtained directly through the <link> or <style> element. The DOM specifies an attribute containing a CSSStyleSheet object called sheet; IE does not support this, but IE supports a similar styleSheet attribute. <BR>function getStyleSheet(element){ <BR>return element.sheet || element.styleSheet; <BR>} <BR>//Get the style sheet introduced by the first <link> element <BR>var link = document .getElementsByTagName("link")[0]; <BR>var sheet = getStylesheet(link); <BR>②CSS Rules<BR>1) The CSSRule object represents each rule in the style sheet and is a resource for other types Inherited base types, the most common of which is the CSSStyleRule type, represents style information. <BR>2) The CSSStyleRule object contains the following attributes: <BR>□cssText: Returns the text corresponding to the entire rule, which is not supported by IE. <BR>□parentRule: If the current rule is an imported rule, this attribute refers to the imported rule; otherwise, this value is null. IE does not support it. <BR>□parentStyleSheet: The style sheet to which the current rule belongs. IE does not support it. <BR>□selectorText: Returns the selector text of the current rule. <BR>□style: A CSSStyleDeclaration object through which you can set and get specific style values ​​in rules. <BR>□type: A constant value representing the rule type. For style rules, this value is 1. IE does not support it. <BR>■The most commonly used attributes are cssText, selectorText and style. <BR>□cssText property is similar to style.cssText property but not the same. The former contains the selector text and curly braces surrounding the style information, the latter contains only the style information (similar to the element's style.cssText). While cssText is read-only, style.cssText is read/write. <BR>var sheet = document.styleSheets[0]; <BR>var rules = sheet.cssRules || sheet.rules; <BR>var rule = rules[0]; <BR>alert(rule.style.backgroundColor) ; <BR>rule.style.backgroundColor="red"; <BR>③ Create a rule <BR>□insertRule() method: accepts two parameters: the rule text and the index expressing where to insert the rule. //IE does not support <BR>sheet.insertRule("body{background-color:silver}",0); //DOM method. <BR>□addRule(): supported in IE. Two required parameters: selector text and CSS style information. An optional parameter: the position to insert the rule. //Only supported by IE<BR>Sheet.addRule("body","background-color:silver",0); <BR>□Cross-browser compatible<BR>function insertRule(sheet, selectorText, cssText, position){ <BR>if(sheet.insertRule){ <BR>sheet.insertRule(selectorText "{" cssText "}", position); <BR>}else if(sheet.addRule){ <BR>sheet.addRule(selectorText, cssText,position); <BR>} <BR>} <BR>Call: insertRule(document.styleSheets[0], "body", "background-color:red", 0); <BR>□When you need to add When there are many rules, the operation is cumbersome. It is recommended to dynamically load style sheets. <BR>④Delete Rules<BR>□sheet.deleteRule(0); //DOM method, IE does not support <BR>Sheet.removeRule(0); //IE method, both pass in the rules to be deleted location. <BR>□Cross-browser compatibility: <BR>function deleteRule(sheet, index){ <BR>if(sheet.deleteRule){ <BR>Sheet.deleteRule(index); <BR>}else if(sheet.removeRule ){ <BR>Sheet.removeRule(index); <BR>} <BR>} <BR>Calling method: deleteRule(document.styleSheets[0],0); <BR>□This approach is not used in actual web development Common practice. Deleting rules will affect the CSS cascading effect. Use with caution. <BR>3. Element size (non-DOM2 style, but supported by all browsers) <BR>①Offset dimension (offset dimension) <BR>Definition: Includes all visible space occupied by the element on the screen. The visible size of an element is determined by its height and width, including all padding, scroll bars, and border sizes (note, margins are not included) <BR>□offsetHeight: The amount of space occupied by the element in the vertical direction, in pixels. <BR>□offsetWidth: The amount of space occupied by the element in the horizontal direction, measured in pixels. <BR>□offsetLeft: The pixel distance between the left border of the element and the contained left inner border.<BR>□offsetTop: The distance in pixels from the top border of the element to the top inner border of the containing element. <BR>△The offsetLeft and offsetTop attributes are related to the containing element, and the reference of the containing element is saved in the offsetParent attribute. The offsetParent property is not necessarily equal to the value of parentNode. <BR>△These properties are read-only and need to be recalculated for each access. If reused, it should be saved in local variables. <BR>②Client area size (client dimension) <BR>The size of the element content and its padding. The space occupied by the scroll bar is not included. <BR>□clientWidth attribute: the width of the element’s content area plus the width of the left and right padding. <BR>□clientHeight attribute: the height of the element’s content area plus the height of the top and bottom padding. <BR>□ Determine the browser viewport size using document.documentElement or document.body (in mixed mode of IE6). <BR>function getViewport(){ <BR>if(document.compatMode == "BackCompat"){ <BR>return{ <BR>width:document.body.clientWidth, <BR>height:document.body.clientheight <BR>}; <BR>}else{ <BR>return{ <BR>width:document.documentElement.clientWidth, <BR>height:document.documentElement.clientHeight <BR>}; <BR>} <BR>} <BR>③Scroll size <BR> refers to the size of the element containing scrolling content. <BR>□scrollHeight: The total height of the element content without scroll bars. <BR>□scrollWidth: The total width of the element content without scroll bars. <BR>□scrollLeft: The number of pixels hidden on the left side of the content area. By setting this property you can change the scroll position of the element. <BR>□scrollTop: The number of pixels hidden above the content area. By setting this property you can change the scroll position of the element. <BR>◇When determining the total height of the document (including the minimum height based on the viewport), the maximum value of scrollWidth/clientWidth and scrollHeight/clientHeight must be obtained to ensure cross-browser. <BR>Var docHeight = Max.max(document.documentElement.scrollHeight,document.documentElement.clientHeight); <BR>Var docWidth = Max.max(document.documentElement.scrollWidth,document.docuemntElement.clientWidth); <BR>Note : For IE running in mixed mode, document.body needs to be used instead of document.documentElement. <BR>◇The scrollLeft and scrollTop attributes can be used to determine the current scrolling state of the element and set the scroll position of the element. <BR>function scrollToTop(element){ <BR>if(element.scrollTop != 0){ <BR>element.scrollTop = 0; <BR>} <BR>} <BR>④Determine the element size<BR>□ IE, Firefox3 and above and Opera9.5 and above provide a getBoundingClientRect() method for each element. This method returns a rectangular object with 4 properties: left, top, right and bottom. These properties give the element's position on the page relative to the viewport. But IE thinks that the upper left corner coordinate is (2,2), and other browsers think it is (0,0). <BR>function getBoundingClientRect(element){ <BR>var scrollTop = document.documentElement.scrollTop; <BR>var scrollLeft = document.documentElement.scrollLeft; <br><br>if(element.getBoundingClientRect){ <BR>If (typeof arguments.callee.offset != "number"){ <BR>var temp = document.createElement("div"); <BR>temp.style.cssText = "position:absolute;left:0;top:0 ;"; <BR>document.body.appendChild(temp); <BR>arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop; <BR>document.body.removeChild(temp); <BR> temp = null; <BR>} <br><br>var rect = element.getBoundingClientRect(); <BR>var offset = arguments.callee.offset; <br><br>return{ <BR>left: rect. left offset, <BR>right: rect.right offset, <BR>top: rect.top offset, <BR>bottom: rect.bottom offset <BR>}; <BR>}else{ <BR>var actualLeft = getElementLeft (element); <BR>var actualTop = getElementTop(element); <br><br>return{ <BR>left: actualLeft - scrollLeft, <BR>right: actualLeft element.offsetWidth - scrollLeft, <BR>top: actualTop - scrollTop, <BR>bottom: actualTop element.offsetHeight - scrollTop <BR>} <BR>} <BR>} <br><br>3. Traversal <BR>①Overview: "DOM2-level traversal and range" module definition Two types are introduced to assist in completing the sequential traversal of the DOM structure: NodeIterator and TreWalker. These two types can perform depth-first traversal operations on the DOM structure based on a given starting point. <BR>□These objects are accessible in DOM-compatible versions. IE does not support traversal. <BR>□Check the browser’s support for DOM level 2 traversal capabilities. <BR>var supportsTraversals = document.implementation.hasFeature("Traversal","2.0"); <BR>var supportsNodeIterator = (typeof document.createNodeIterator == "function"); <BR>var supportsTreeWalker = (typeof document.createTreeWalker == "function"); <BR>②NodeIterator <BR>1) You can use the document.createNodeIterator() method to create a new instance of it. <BR>Accepts 4 parameters: <BR>□root: The node of the tree species that you want to use as the starting point of the search. <BR>□whatToShow: Numeric code indicating which nodes to visit. <BR>□filter: It is a NodeFilter object, or a function that indicates whether a specific node should be accepted or rejected. <BR>□entityReferenceExpansion: Boolean value, indicating whether to extend the entity reference. This parameter has no use in HTML pages. <BR>■The whatToShow parameter is a bitmask whose value is defined in the NodeFilter type as a constant.<BR>□NodeFilter.SHOW_ALL: Display all types of nodes. <BR>□NodeFilter.SHOW_ELEMENT: Display element nodes. <BR>□NodeFilter.SHOW_ATTRIBUTE: Display attribute nodes. Due to DOM structure reasons, this value cannot actually be used. <BR>□NodeFilter.SHOW_TEXT: Display text nodes. <BR>□NodeFilter.SHOW_CDATA_SECTION: Display CDATA nodes. Useless for HTML. <BR>□NodeFilter.SHOW_ENTITY_REFERENCE: Display entity reference nodes. Useless for HTML. <BR>□NodeFilter.SHOW_ENTITYPE: Display entity nodes. Useless for HTML. <BR>□NodeFilter.SHOW_PROCESSING_INSTRUCTION: Display processing instruction nodes. Useless for HTML. <BR>□NodeFilter.SHOW_COMMENT: Display comment nodes. <BR>□NodeFilter.SHOW_DOCUMENT: Display document nodes. <BR>□NodeFilter.SHOW_DOCUMENT_TYPE: Display document type nodes. <BR>□NodeFilter.SHOW_DOCUMENT_FRAGMENT: Display document fragment nodes. Useless for HTML. <BR>□NodeFilter.SHOW_NOTATION: Display symbol nodes. Useless for HTML. <BR>◇In addition to NodeFilter_SHOW_ALL, multiple options can be combined using the bitwise OR operator. <BR>var whatToShow = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT; <BR>◇Use the filter parameter to customize a NodeFilter object or a filter function. <BR>The NodeFilter object has only one method, acceptNode(). If accessed, NodeFilter.FILTER_ACCEPT will be returned. If not accessed, NodeFilter.FILTER_SKIP will be returned. <BR>Example 1: Iterator <BR>var filter= { <BR>acceptNode:function (node)P{ <BR>return node.tagName.toLowerCase()=="p" ? <BR>NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; <BR>} <BR>} <BR>}; <BR>var iterator = document.createNodeIterator(root,NodeFilter.SHOW_ELEMENT,filter,false); <BR>Example 2: The filtr parameter can also be a function similar to the acceptNode method. <BR>var filter = function(node){ <BR>return node.tagName.toLowerCase() == "p" ? <BR>NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; <BR>}; <BR>var iterator = document.createNodeIterator(root,NodeFilter.SHOW_ELEMENT,filter,false); <BR>2) There are two main methods of NodeIterator type: nextNode() and previousNode(). <BR>var div = document.getElemetnById("div1"); <BR>var iterator = document.createNodeIterator(div,NodeFilter.SHOW_ELEMENT,null,false); <BR>var node = iterator.nextNode(); <BR>while(node ​​!== null){ <BR>alert(node.tagName); <BR>node = iterator.nextNode(); <BR>} <BR>③TreeWalker <BR>1) TreeWalker is an update of NodeIterator Premium version. In addition to nextNode() and previousNode(), there are also the following methods for traversing the DOM structure in different directions: <BR>□parentNode(): Traverse to the parent node of the current node. <BR>□firstChild(): Traverse to the first child node of the current node. <BR>□lastChild(): Go to the last child node of the current node. <BR>□nextSibling(): Traverse to the next sibling node of the current node. <BR>□previousSibling(): Traverse to the previous sibling node of the current node. <BR>2) To create a TreeWalker object, use the document.createTreeWalker() method, which accepts 4 parameters, the same as the document.createNodeIterator() method. <BR>□ In addition to returning NodeFilter.FITER_ACCEPT and NodeFilter.FILTER_SKIP, the third parameter filter return value can also use NodeFILTER_REJECT (function: skip the corresponding node and the entire subtree of the node). <BR>□The power of TreeWalker is that it can move in any direction in the DOM structure. <BR>◇Example: Traverse the DOM tree and obtain all <li> elements even without defining a filter. <BR>var div = document.getElementById("div1"); <BR>var walker = document.createTreeWalker(div,NodeFilter.SHOW_ELEMENT,null,false); <BR>walker.firstChild(); <BR>walker. nextSibling(); <BR>var node = walker.firstChild(); <BR>while(node ​​!== null)} <BR>alert(node.tagName); <BR>node = walker.nextSibling(); <BR>} <BR>□The TreeWalker type also has an attribute called currentNode, which represents the node returned by any traversal method in the previous traversal. <BR>4. Scope <BR>Basic definition: <BR>Scope allows you to select an area in the document without considering the boundaries of the nodes (the selection is completed in the background and is invisible to the user). When the document cannot be modified more efficiently through regular DOM manipulation, using scopes often does the trick. <BR>1. Range in DOM <BR>①Overview: <BR>1) DOM2 level defines the createRange() method in the Document type. <BR>□Check whether the range is supported: <BR>var supportsRange = document.implementation.hasFeature("Range","2.0"); <BR>var alsoSupportsRange = (typeof document.createRange == "function"); <BR>□Create DOM range: var range = document.createRange(); <BR>2) In the Range type instance, the attribute that provides the position information of the current range in the document: <BR>□startContainer: The node containing the starting point of the range (i.e. The parent node of the first node in the selection) <BR>□startOffset: The offset of the starting point of the range in startContainer. If StartContainer is a text node, startOffset is the number of characters skipped before the start of the range. Otherwise, startOffset is the index of the first child node in the range within the parent node. <BR>□endContainer: Contains the node at the end of the range (that is, selects the parent node of the last node).<BR>□endOffset: The offset of the end point of the range in endContainer (rules such as startoffset) <BR>□commonAncestorContainer: The common ancestor node of startContainer and endContainer is the one with the deepest position in the document tree. <BR>②Use DOM range to implement simple selection: <BR>1) Use range to select a part of the document: <BR>□selectNode(): Pass in a DOM node and select the entire node, including sub-nodes as a range. <BR>□selectNodeContents(): Pass in a DOM node and select only child nodes as the range. <BR>2) Control the range more precisely: <BR>□setStartBefore(refNode): Set the starting point of the range before refNode, so refNode is the first child node in the range selection. The range's location properties are updated automatically. <BR>□setStartAfter(refNode): <BR>□setEndBefore(refNode): <BR>□setEndAfter(refNode): <BR>③ Use DOM range to implement complex selection: <BR>□setStart(): Pass in a reference point and an offset. The reference node becomes startContainer, and the offset becomes startOffset. <BR>□setEnd(): Pass in a reference point and an offset. The reference node becomes endContainer, and the offset becomes endOffset. <BR><p id="p1"><b>Hello world!//Use the range to select l to o. <BR>var p1 = document.getElementById("p1"); <BR>var helloNode = p1.firstChild.firstChild; <BR>var worldNode = p1.lastChild; <BR>var range = document.createRange(); <BR>range.setStart(helloNode,2); <BR>range.setEnd(worldNode,3); <BR>④Manipulate the content in the DOM range<BR>□When calling the operation method, the background will create a valid value for the range Document fragments and DOM structure. P275 <BR>□deleteContents(): Delete the content contained in the range from the document. <BR>□extractContents(): Remove range content from the document and return the range document fragment. <BR>⑤Insert content in the DOM range <BR>□insertNode(): Insert a node to the beginning of the range selection. <BR>□surroundContents(): Accepts one parameter, which is the node surrounding the content of the range. <BR>a. Extract the content in the range (similar to executing extractContent()) <BR>b. Insert the given node into the document at the location of the original range. <BR>c. Add the content of the document fragment to the given node. <BR>⑥Collapse DOM range <BR>□The so-called folding range refers to any part of the unselected document in the range. <BR>□collapse() method: one parameter Boolean value. true to collapse to the beginning of the range, false to collapse to the end of the range. You can use the collapsed attribute to check whether it has been collapsed. <BR>range.collapse(true); //Collapse to the starting point<BR>alert(range.collapsed); //Output true <BR>⑦Compare DOM range<BR>Can be used when there are multiple ranges compareBoundaryPoints() method to determine whether these ranges have a common boundary (start or end). Two parameters: a constant indicating the comparison method and the range to be compared. <BR>Comparison method constant value: <BR>□Range.START_TO_START(0): Compare the first range and the starting point of the second range. <BR>□Range.START_TO_END(1): <BR>□Range.END_TO_END(2): <BR>□Range.END_TO_STRAT(3): <BR>⑧Copy DOM range<BR>□cloneRange() method: var newRange = range.cloneRange(); <BR>⑨Clean up the DOM range<BR>□Call the detach() method to separate the range from the document. <BR>range.detach(); //Detach from the document<BR>range = null; //Dereference<BR>2. Range in IE<BR>①Overview: <BR>□IE does not support DOM range . Similar text ranges are supported. <BR>□The text range mainly handles text (not necessarily DOM nodes). The createTextRange() method is called through elements such as <body>, <button>, <input> and <textarea>. <BR>□Scopes created through document can be used anywhere in the page. <BR>var range = document.body.createTextRange(); <BR>②Use IE range to implement simple selection<BR>□findText() method: find the first occurrence of the given text and move the range over to surround the text. Returns a Boolean value indicating whether the text was found. <BR>◇Use the text attribute to return text in the range. <BR>var range = document.body.createTextRange(); <BR>var found = range.findText("Hello"); <BR>◇You can pass in another parameter for findText. A negative value means the current position is searched backward. , if the value is positive, search forward. <BR>□moveToElementText() method: similar to the selectNode() method in DOM. Accepts a DOM element and selects all text of that element, including HTML tags. <BR>◇The range can use the htmlText attribute to obtain the entire content of the range, including HTML. <BR>③Use IE range to implement complex selection <BR>□4 methods: move(), moveStart(), moveEnd(), expand(); two parameters: moving unit and number of moving units. The movement unit is the following string: <BR>◇"character": Move character by character. <BR>◇"word": word by word (move as a series of non-space characters) <BR>◇"sentence": sentence by sentence (move as a series of characters ending with a period, hello or exclamation point) <BR>◇"textedit" : Move to the beginning or end of the current range selection. <BR>□moveStart(): Move to the starting point of the range; moveEnd() moves to the end point of the range. <BR>□expand(): Select all selected text in any part. <BR>□move() method: First, the current range will be folded (the starting point and end point are equal), and then the range will be moved by the specified number of units. <BR>④ Manipulate the content in the IE range <BR>□The range only contains text, and you can read and write text through the text attribute. <BR>□pasteHTML() method: Insert HTML code into the range. <BR>⑤Collapse IE range <BR>□collapse() method: Pass in a Boolean value, true to collapse to the starting point, false to collapse to the end point. <BR>□Check whether the folding is complete: the boundingWidth attribute is equal to 0 <BR>var isCollapse = (range.boundingWidth == 0); <BR>⑥Compare IE range<BR>□compareEndPoints() method: two parameters: comparison type and the range to be compared. <BR>◇Comparison type value string: "startToStart", "StartToEnd", "EndToEnd" and "EndToStart". <BR>◇If the first range boundary is before the second one, return -1; if equal, return 0; if after, return 1. <BR>□isEquanl() is used to determine whether two ranges are equal. <BR>□inRange() is used to determine whether a range contains another range. <BR>⑦Copy IE range <BR>Use the duplicate() method to copy the text range and return a copy. <BR>var newRange = range.duplicate();</script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn