Xiao Kee
Expand on the basis of DOM1, introduce more interactions, and process more advanced XML. It is divided into many application modules, describing the functions of DOM2 and DOM3, including: DOM2-level core, DOM2-level view, DOM2-level event (13 chapters), DOM2-level style, DOM2-level traversal and scope, DOM2-level HTML, The DOM3 class adds XPath modules and loading and saving modules, which are discussed in Chapter18. This chapter discusses:
- Dom Change: namespace (XHML and XHL, not much related to HTML), document programmatic operation. Go
- Dom Style changes: This is more important for HTML. Style property, getComputedStyle ()/currentstyle, document.stylesheets, and related IE interface go
- Traversal (depth first): Nodeiterator (moves at one node's stride), TreeWalker go
- Scope: You can select a portion of a document, hand it over to a document fragment, and then perform other actions on it. The corresponding text range can be manipulated in IE. Go
Dom Changes (discusses DOM2-level cores, HTML and view modules, and some DOM3)
- Detect if Dom core, HTML, and view modules are supported
var supportsdom2core = document.implementation.hasFeatrue ("Core", "2.0"); var supportsdom3core = document.implementation.hasFeatrue ("Core", "3.0"; var supportsdom2html = Document.implementation.hasFeatrue ("HTML", "3.0"); var supportsdom2views = document.implementation.hasFeatrue ("views", "2.0"); var supportsdom2xml = document.implementation.hasFeatrue ("XML", "2.0");
- Changes to namespaces (primarily XML namespaces, for example in XHTML)
- Knowledge of namespace-related concepts: prefix, LocalName, TagName (nodeName), NamespaceURI. You can also specify namespaces for properties
- Change of node type
- Properties: LocalName, NamespaceURI, prefix
- Method (DOM3): Isdefaultnamespace (NamespaceURI)/lookupnamespaceuri (prefix)/lookupprefix (NamespaceURI)
- Change in document type
- Method: Createelementns (NamespaceURI, TagName)/createattributens (NamespaceURI, AttributeName)/getelementsbytagnamens ( NamespaceURI, TagName)
- Change of element type
- How to operate the feature (DOM2): Getattributens (NamespaceURI, LocalName)/getattributenodens (namespaceuri,localname)/ Getelementsbytagnamens (NamespaceURI, TagName)/hasattributens (NamespaceURI, LocalName)/removeattributens ( NamespaceURI, LocalName)/setattributens (NamespaceURI, QualifiedName, value)/setattributenoadens (AttNode)
- NamedNodeMap Types of changes (attribute related operations, less use)
- Getnameditemns (NamespaceURI, LocalName)/removenameditemns (Namesaceuri, LocalName)/setnameditemns (node)
- Other changes (non-namespace aspects)
- DocumentType type: publicID, SystemID, Internalsubset
- Document type: ImportNode () method
- Meaning: Each node has a ownerdocument attribute that represents its document attribution. If you are simply copying between different documents, there is a problem with the Ownerdocument property, and when you use AppendChild ().
- ImportNode (OldNode, True) produces a copy of the original node and can be added to another document. Note that the second parameter, if true, is copied along with its child nodes. (Common to XML documents)
- DOM2-level View: DefaultView property, holds the pointer, points to the window or frame of the given document. IE uses ParentWindow instead:
var ParentWindow = Document.defaultview | | Document.parentwindow;
- DOM2-level cores: Document.implementation's CreateDocumentType () and CreateDocument () methods, which are typically used in conjunction with the third parameter of the latter for the attributes created by the former. To create a document.
- DOM2 level HTML:document.implementation.createHTMLDocument () method, create a containing
- Change of node type
- The IsSupported () method, similar to the Hasfeature () method, is also used in conjunction with the lack of attention and capability detection.
- DOM3-Level Auxiliary comparison node:
Issamenode ()/isequalnode (). The former emphasizes that the referenced nodes should be the same, the latter emphasizing the attributes of the nodes equal.
Setuserdata ("name", "Nicholas", function () {}) adds additional data to the node. The function of the third parameter can perform a specific operation when the node is associated with the operation (copy, import, delete, rename).
- Framework changes (frame)
- Htmlframeelement/htmliframeelement representing frames and inline frames
- Contentdocument property: Pointer to the Document object that represents the content of the frame, IE uses Contentwindow instead:
var iframe = getElementById ("Myiframe");
var iframedoc = Iframe.contentdocument | | Iframe.contentWindow.document;
- Note the limitations and effects of cross-domain security policies.
Style (DOM's style module)
-
-
- Length and item () can be used interchangeably, at which point the style is considered an array of objects.
- The GetPropertyValue () method obtains the property value, and the Getpropertycssvalue () method gets the property value and the type of the value.
- Calculated style: You have experienced overlapping styles, and you can get styles from the style sheet.
- Document.defaultView.getComputedStyle () method, parameter is the element to get the calculated style and the pseudo-element information (the latter if it is not written as null)
- IE uses the Currentstyle attribute instead, which is an example of cssstyledeclaration.
- The calculation style is read-only.
- Manipulating style sheets (unifying style elements and link elements)
- Cssstylesheet object: Inherits from stylesheet. Unified processing of htmllinkelement and htmlstyleelement, but the latter two can modify the attributes, the former is only read-only.
- Varsupportsdom2stylesheets =document.implementation.hasfeatrue ("stylesheets", "2.0");
- Inherited attributes:
-
- In addition to the properties and methods (handling rules)
-
- Document.stylesheets The style sheets returned in different browsers are different. IE and opera also return a style sheet that is set to "Alternatestylesheet" in rel.
- can be obtained directly through the link or style element cssstylesheet,dom a sheet,ie is used stylesheet (previously mentioned document.stylesheets)
function Getstylesheet (Element) {
return Element.sheet | | element.stylesheet
}
- CSS rules: Cssstylerule objects that contain commonly used attributes Csstext,selectortext and style. Get rule: document.stylesheets[0].cssrules| | Document.stylesheets[0].rules;
- Create rule: insertrules () method, ie with addrule () instead. If you need to add more rules, you may want to use the dynamic introduction of the style sheet mentioned earlier methods.
- Delete rule: Deletrules () method, ie with Removerule () method.
- Element size (space occupied)
- Offset: offsetheight/offsetwidth (in pixels, including content area, scroll bar, upper/lower/left border. does not contain margin), offsetleft/offsettop (left/sisu border to the pixel value between the left/top inner border of the containing element)
- Note the Offsetparent property is not necessarily equal to the ParentNode property. For example, the offsetparent of <td> points to <table>, because the latter is the closest element in the DOM hierarchy to the size of <td>.
- Offset on page: The offsetleft of the element and the offsetleft of its outer container are added to the root element node.
- The Offset property is read-only and avoids the efficiency of multiple reuse effects.
- Customer area size (the amount of space the element content and its padding occupies): clientwidth/clientheight:
-
- Scrolling size: scrollheight/scrollwidth, Scrollleft/scrolltop,
-
- When determining the total document height, you must obtain the maximum value in Scrollwidth/clientwidth, Scrollheight/clientheight.
- As mentioned before, the application of the above attributes and methods on Document.body or document.documentelement requires a specific distinction.
- Determine the element size:
- The position of the element in the page relative to the viewport: left, top, right, bottom through the Getboundingclientrect () method
- However, starting point offset differs and may not have this method, so you need to construct this method yourself: PDF p344-345
Traversal (Nodeiterator and Treewalker)
var supportsTraversals = Document.implementation.hasFeature ("Traversal", "2.0" var supportsNodeIterator = ( typeof document.createNodeIterator == ' function ' var supportsTreeWalker = ( typeof document.createTreeWalker == ' function ');
- Depth-first traversal: Two directions-up or down. Explore the depths first, then traverse the next depth.
- Nodeiterator (traverse with one node for stride)
- TreeWalker (Advanced version, more powerful nodeiterator)
- Document.createtreewalker (Root, Whattoshow, filter, entityreferenceexpansion)
- The method or function at the FILTER can return a value more than Nodeiterator: Nodefilter.filter_reject (does not traverse a node that does not meet the criteria and its child nodes); nodefilter.filter_ Skip just skips a node that doesn't meet the criteria.
- Methods: NextNode ()/previousnode (), ParentNode (), FirstChild ()/lastchild (), nextSibling ()/previoussibling ().
- Property: CurrentNode
- With the above methods and properties, Treewalker can imagine moving in any direction or even stride in the node tree. It is important to note that the Walker pointer in the following example is dynamically changing, which is the embodiment of "traversal".
-
-
- HTML code
<DivID= "Div1"> <P><b>Hello</b>world!</P> <ul> <Li>List Item 1</Li> <Li>List Item 2</Li> <Li>List Item 3</Li> </ul> </Div>
- JS Code
var div = document.getElementById ("Div1"); var NULL false // go to <p>walker.nextsibling (); // go to <ul> // go to the first <li>
Range (selects an entire area and then operates on it)
var supportsrange = document.implementation.hasFeature ("Range", "2.0"); var alsosupportsrange = (typeof Document.createrange = = "function");
- Create scope: Createrange () creates an instance, Selectnode ()/selectnodecontents () makes a range selection (the former selects the entire node, the latter selects the child node), Startcontainer/startoffset, Endcontainer/endoffset, Commonancestorcontainer property is dynamically refreshed. Take the following code as an example:
- HTML code
<DivID= "Div1"> <P><b>Hello</b>world!</P> <ul> <Li>List Item 1</Li> <Li>List Item 2</Li> <Li>List Item 3</Li> </ul> </Div>
- JS Code
var range1 = document.createrange (); var range2 = document.createrange (); var p1 = document.getElementById ("P1"); Range1.selectnode (p1); Range2.selectnodecontents (p1) ;
- Analysis:
Range1 using Selectnode () for range selection, its startcontainer/endcontainer/commonancestorcontainer are all elements <p> The parent node of the document.body (Commonancestorcontainer should satisfy: common, deepest). Startoffset equals the position of the given node <p> in the parent element ChildNodes Index 1 (considering that the DOM takes the preceding space as 0). Endoffset equals startoffset+1 (because only one node is selected).
Range1 use Selectnodecontents () to select, as the name implies, its startcontainer/endcontainer/commonancerstorcontainer are incoming node <p>. Startoffset is 0,endoffset is obviously the length of the child element of P, here is 2.
- There are also ways to further control whether a node is contained in a range: Setstartbefore ()/setstartafter ()/setendbefore ()/setendafter () as the name implies.
- To achieve a more complex or elaborate choice:
- Setstart (Startcontainer,startoffset)/setend (Endcontainer,endoffset)
- Function: Simulates Selectnode () or selectnodecontents (), part of the selection (text) node
- Manipulate the contents of the DOM range:
- Important knowledge: Internally a document fragment is created for the range, and this fragment has a complete and reasonable construct for further use.
- Delete range: DeleteContents ()
- "Extraction" Range: extractcontents (). This fragment is returned in addition to the deletion.
- Copy Range object: Clonecontents () Creates a copy of the scope object.
- Insert content in range: Insertnode (): Note If you do not experience the above operation, no additional tags or structures will be created in the background.
- Wrapping inserted content: Surroundcontents ()
- Collapse Dom Range: Collapse (). Collapse to the start point true or the end point false,collapsed can determine if there is any folding.
- Compare Dom Range: compareboudarypoints (). Axis Dafa: In the front-1, in the last 1, the same point 0.
- Replication range: Clonerange (). Modifying the replica endpoint does not affect the original scope, and clonecontents () replicates an object that points to the same area, so it has an impact.
- Cleaning range: Range.detach (); range=null;
- Some alternatives to the scope in IE8 and earlier versions:
- Main processing text range: Creattextrange () creates a text Range object.
- The FindText () parameter is text, selects the first qualifying text, and moves the range around the text. Returns True when found, otherwise false. You can also pass in another parameter that represents the direction of the search, with negative values backwards and positive values forward.
- Movetoelementtext () is similar to Selectnode (). Accepts an element and selects all text for that element. All content within the range can be obtained through htmltext.
- Parentelement similar to Commonancestorcontainer as a dynamic indicator.
- Complex range: Move ()/movestart ()/moveend/expand () moves the range around. Accepts two parameters: Move the unit and move the quantity.
- Manipulating the content of IE range
- Modify the scope content: either by the Text property or by the Pastehtml () method.
- Collapses the IE Range: collapse () and determines whether to collapse through the Boundingwidth property.
- Compare IE Range: compareendpoints (), or the axis of Dafa. IsEqual ()/inrange () as the name implies.
- Copy IE Range: Duplicate ()
JavaScript Advanced Programming Chapter DOM2 and DOM3