Follow the WEB standard to explore DOM--the traversal of Node and Element

Source: Internet
Author: User
Tags naming convention

Write in front

This article does not have any WebKit code analysis, because ... No good analysis, in the implementation is nothing more than a tree (first-order Dfs) traversal just, embarrassed hahaha ... Look at the WebCore/dom/Node.h WebCore/dom/ContainerNode.h two eyes in, and WebCore/dom/Element.h the corresponding. cpp. The following properties are generally used as private variables directly in the object (basically called by the naming convention) and m_xxx then returned by the public method with the same name as the standard. Note, however, that where they are placed, for example, Node the methods associated with child nodes are generally defined in the ContainerNode.h, Node where it is important to realize that Element the methods that exist are generally Element.h (even when defined Node::xxx ).

This article analyzes the differences between the elements that are Node and the elements that act as element, and summarizes the compatibility of each browser with these APIs.

NodeThe traversal

NodeInheritance,,, EventTarget Document inheritance, DocumentFragment Element Node so the properties mentioned below Document , DocumentFragment Element can all be used.

Node.parentNodeStandard

DOM 1 is defined in Node interface, prototypes readonly attribute Node parentNode , indicated Document , and not in the DocumentFragment Attr tree node parentNode null .

Dom 2,dom 3,whatwg,dom 4 is consistent with Dom 1

Watch out.

This is a read-only property, so you cannot move it by assigning a value to an element parentNode , and any assignment to that reference will be ignored. Like what:

Node.parentnode =//  false

However, you can modify its parentNode properties.

Node.parentNode.title = "foo"//  foo

In addition, Document and Attr there is no parentNode good understanding, but Attr not a bit difficult to understand, and Entity there is Notation no-reverse understanding, Node.childNodes is not counted attribute node,entity node, etc. You don't need to be a parent when you are a child.

This property with no parent Node (for example, just createElement created or removeChild deleted) is null.

Compatibility

parentNodeThere are several bugs in the ie8-:

The newly created element parentNode is NULL, but the modified content (for example, with innerHTML or appendChild ) becomesDocumentFragment

var foo = document.createelement (' div '); Console.log (Foo.parentnode);   // nullfoo.innerhtml = "Bar"Console.log (Foo.parentnode);   // [Object HTMLDocument]console.log (foo.parentNode.nodeType);  // One = DocumentFragment

The node that was deleted from the document parentNode is DocumentFragment . To the following HTML:

<id= "foo">    <id= "Bar" ></ Div > </ Div >

Execute JS:

var foo = document.getElementById (' bar '); Console.log (Foo.parentnode);   // [Object Htmldivelement] Foo.parentNode.removeChild (foo); Console.log (Foo.parentnode);   // [Object HTMLDocument]console.log (foo.parentNode.nodeType);  // One = DocumentFragment
Node.firstChildAnd Node.lastChildStandard

DOM 1 ( firstChild , lastChild ) is defined in Node interface, prototype readonly attribute Node firstChild and readonly attribute Node lastChild , indicating Document , DocumentFragment Attr and not in the tree node parentNode null .

Dom 2 ( firstChild , lastChild ), Dom 3 (,), firstChild lastChild WHATWG ( firstChild , lastChild ), Dom 4 ( firstChild , lastChild ) and Dom 1 are consistent

Watch out.

This is a read-only property, and the parentNode same cannot be re-assigned.

Note that the browser may (and many) place the text node and comment node in a node's child nodes (the indentation and breaking of the HTML text will be counted as the new text node in between elements), and document.firstNode may be D Octype, so it is not possible to determine the firstChild return of an element, if you want the first element, you need to manually check nodeType and filter backwards.

The CSS pseudo element is not counted.

The FAQ explains why a DOM implementation would count white space characters as text node:

The DOM must have processed XML (and for convenience, many DOM implementations will combine XML with many of the HTML processing) the original text to the application, the white space character can not be discarded (so that the DOM tree and XML text to complete the one by one mapping), then you should find a type of no The de plugs it in--the most appropriate is the text node.

Compatibility

IE 8-do not count the blank text node as child nodes, ie + + and other browsers are counted. To the following HTML:

<id= "foo"></div>

Execute JS:

var foo = document.getElementById (' foo '); Console.log (foo.firstchild);   // NULL in ie8-, supposed is a text node
Node.nextSiblingAnd Node.previousSiblingStandard

DOM 1 ( previousSibling , nextSibling ) is defined in Node interface, prototype, readonly attribute Node previousSibling and readonly attribute Node nextSibling does not exist for the return of the corresponding node null .

Dom 2 ( previousSibling , nextSibling ), Dom 3 ( previousSibling , nextSibling ) and Dom 1 are the same.

WHATWG ( previousSibling , nextSibling ) is consistent with the DOM, and also illustrates the concept of sibling and the concept of relative position in the tree (according to tree order, first-order Dfs)

DOM 4 ( previousSibling , nextSibling ) is consistent with WHATWG.

Watch out.

and Node.firstChild Node.lastChild similar to the precautions.

Compatibility

IE 8-Do not count blank text node as Sibling,ie + + and other browsers.

Html:

< Div ></ Div >  <  ID= "foo"></div>

Js:

var foo = document.getElementById (' foo '); // [Object Htmldivelement] in ie8-, supposed to bes a text nodeconsole.log (foo.previoussibling);
Node.childNodesStandard

DOM 1 is defined in Node interface, the prototype readonly attribute NodeList childNodes , indicating that the return NodeList is live, and that if no child nodes are returned empty NodeList .

Dom 2,dom 3 and Dom 1 are the same.

The WHATWG prototype [SameObject] readonly attribute NodeList childNodes is consistent with the DOM. DOM 4 is the same as WHATWG.

Watch out.

and Node.firstChild Node.lastChild similar to the precautions. The returned NodeList element is read-only (you can change the element property and cannot be referenced). It is useless to use your brains if you want to delete or subtract the child elements. childNodes (Note: Other browser childNodes references to the changes are only ignored, but IE will be angry error)

Html:

<id= "foo"><p></p> </div>

Js:

varFoo = document.getElementById (' foo ')); Console.log (foo.childNodes.length); //1varBar = document.createelement (' div '); foo.childnodes[0] = bar;//attempt to replace a child, throws error in IEConsole.log (Foo.childnodes[0].nodename);//"P", not replacedfoo.childnodes[1] = bar;//attempt to add a child, throws error in IEConsole.log (foo.childNodes.length);//1, not addedDeleteFoo.childnodes[0];//attempt to delete a child, throws error in IEConsole.log (foo.childNodes.length);//1, not deleted

Generally document.childNodes only doctype and elements, unless there is a comment between the original text.

The order of the elements is the document order, which is arranged according to the first-order DFS in the DOM tree.

Compatibility

IE 8-do not count the blank text node as child nodes, ie + + and other browsers are counted.

Html:

<id= "foo">   </div>

Js:

var foo = document.getElementById (' foo '); // 0 in ie8-, supposed to be 1console.log (foo.childNodes.length);
ElementThe traversal

ElementNodethe difference is Element not including the text node,comment node,etc. In fact, Element inherit from Node , that is, it is Node a kind of. Have Element (or should have) Node.nodeType == Node.ELEMENT_NODE this feature (there are several other things nodeType to see WHATWG standards, which are not described here first). The following APIs can be seen Node as API plus filtering the results Node.nodeType == Node.ELEMENT_NODE (in fact WebKit implementations are basically doing the same).

Note that Element the traversal API as a basic is a new feature of HTML5, which is generally found only in DOM 4.

Node.parentElementStandard

WHATWG will be parentElement defined in Node, prototype readonly attribute Element? parentElement . The same is true for DOM 4.

At first glance, the definition Node seems a bit strange, but careful thinking is actually very reasonable- Element the child node is not necessarily Element , such as text node. You can't hinder the ability of others to tracing:D

Watch out.

If Node the parent element is not Element , the return is null.

Compatibility

In fact parentElement , it started with IE (at least from IE6), but IE only Element defines this attribute (i.e., text node is not available). Since then this attribute entered the standard, the basic major browsers are supported it, the main compatibility problem occurs in IE does not support Element the Node use of this property. If you only Element use it, you can use it with confidence.

In addition, due to the ie8-of the parentNode bug (see above), in only Element the desired scenario, may be used parentElement is a better choice.

ParentNode.firstElementChildAndParentNode.lastElementChildStandard

Currently WHATWG will be firstElementChild and lastElementChild defined in the ParentNode prototype for

ReadOnly attribute Element? Firstelementchild; ReadOnly attribute Element? Lastelementchild;

They were originally ElementTraversal , and later, in order to reduce the coupling, the WHATWG would be ElementTraversal divided into two interface according to the function, and the ParentNode ChildNode firstElementChild lastElementChild Nature would remove the setting for the child element Node ParentNode .

The current inheritance ParentNode includes Document , Element and DocumentFragment , so these three interface objects are accessible firstElementChild and available lastElementChild .

The DOM4 and WHATWG the same, but note DOM4 is not a recommendation. Currently in the recommendation State of the standard, firstElementChild and lastElementChild still defined in ElementTraversal . All must be achieved in accordance with the Element traversal standard, Element ElementTraversal but no other interface are required.

Therefore, these two attributes differ in the WHATWG and the standard of the WHATWG: The standard, Document Element and DocumentFragment both of these properties; In the standard, there are only Element these two properties. But because DOM4 and WHATWG are likely to become the world's most RECOMMENDATION,W3C standard in the future, it is likely that the three objects will have these two properties, like WHATWG.

Watch out.

If there are no child elements, the return is null. These two properties are also read-only and can be modified on a child element, but cannot be changed (ignored).

Compatibility

Due to the newer API, Element on the use of IE + + support, the current version of other browsers are supported.

Because there are differences in the current standards of WHATWG and the Document Web, and DocumentFragment support for these two attributes are not consistent across browsers. Partial WHATWG of Chrome,firefox and Opera support Document , Element and DocumentFragment , IE + + and Safari support only Element . Considering that DOM4 in the future should become a world recommendation, and finally should be three interface can support (of course, IE can not be expected to support the old version of ... )

NonDocumentTypeChildNode.nextElementSiblingAndNonDocumentTypeChildNode.previousElementSiblingStandard

In the WHATWG standard, and in order to take care of jQuery compatibility for getElementById a special NonElementParentNode (rather than ParentNode ) similar, in order to care for the compatibility of existing Web pages, nextElementSibling and previousElementSibling is defined in a specialized division NonDocumentTypeChildNode (rather than

NonDocumentTypeChildNodethe current definition is as follows:

[nointerfaceobject] interface Nondocumenttypechildnode {  readonly attribute Element? previouselementsibling;  ReadOnly attribute Element? Nextelementsibling;} ; Element implements Nondocumenttypechildnode; Characterdata implements Nondocumenttypechildnode;

Note: The current WHATWG standard ParentNode , NonElementParentNode , ChildNode and NonDocumentTypeChildNode the relationship between:

The DOM4 is consistent with the WHATWG, but similar to the situation with the same, according to the ParentNode.firstElementChild ParentNode.lastElementChild current recommendation Element traversal definition, only Element have these two properties, CharacterData No.

Watch out.

Similar ParentNode.firstElementChild and ParentNode.lastElementChild .

Compatibility

Also with ParentNode.firstElementChild and ParentNode.lastElementChild similar, need ie9+. Chrome,firefox and Opera support Element and CharacterData on access to these two properties, IE + + and Safari only support Element , if the world's DOM 4 into the recommendation, is likely to be unified.

ParentNode.childElementCountStandard

WHATWG/DOM4 defined in ParentNode , prototypes readonly attribute unsigned long childElementCount . The recommendation is now defined ElementTraversal as prototypes and WHATWG.

Watch out.

In an implementation that conforms to the standard, approximately equals container.children.length .

Compatibility

And ParentNode.firstElementChild The situation is similar, requires Ie9+,chrome,firefox and Opera support Document , Element and DocumentFragment , IE + + and Safari support only Element .

ParentNode.childrenStandard

Although this API existed very early, it was not standardized until recently. WHATWG/DOM4 is defined in the ParentNode prototype [SameObject] readonly attribute HTMLCollection children , which indicates that it is a live HTMLCollection rather than, that is to say, the NodeList element must be all (the embarrassing name of the legacy problem, and the name of the other side, not the Element Node number, not called childElements children, not called ElementList HTMLCollection ... )。

Watch out.

Similarly Node.childNodes , the resulting HTMLCollection is live and (referenced) read-only.

Compatibility

This attribute was first seen in IE and IE6 began to have this property. After that, Firefox was the last major browser to implement this property (3.5, and quite a long time). But because the WHATWG standard is different in acceptance, Chrome,firefox and Opera are supported Document , Element and DocumentFragment on the use of this attribute, IE and Safari are only supported Element . Chrome and Firefox also experimentally support the use of SVGElement this property on.

In addition, the ie8- children will contain comment node.

Html:

<id= "foo"><!-- - </div>

Js:

var foo = document.getElementById (' foo '); Console.log (foo.children.length);   // 1, supposed to be 0

Follow the WEB standard to explore DOM--the traversal of Node and Element

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.