Talk about the DOM thing.

Source: Internet
Author: User
Tags tagname chrome developer

Intro

First, a chestnut:

< img src="/sub/123.jpg"alt="Test"/><script type="Text/javascript">var img = document.getelementsbytagname (' img ') [0]; Console.log (' src: ', img.src); </ Script >

Output src:sub/123.jpg? No, the output is src:http://127.0.0.1:8020/sub/123.jpg, but I actually just want a pathname. Although there are 10,000 ways to remove pathname from the full address, I would like to get the src that we wrote to the attribute once.

Of course, such an interface must be:

Console.log (' src: ', img.getattribute (' src ')); //src:/sub/123.jpg

In the past, I always feel that there are not many things in HTML, but now found that they do not know much, or too naive ah! The DOM structure is so unfamiliar. Found the problem, and went back to look at the elevation 3, always feel that in accordance with the DOM123 classification is not logical, or try to follow the function of the summary of the difference.

DOM node

First look at the DOM structure level, the last chestnut:

<! DOCTYPE html><HTML><Head><Meta CharSet="UTF-8"><title>Dom</title></Head><Body><!--wrapper--><Div class="WRP">Wrp<img src="/sub/123.jpg" alt="Test" /><Script type="Text/javascript">var img = document.getelementsbytagname (' img ') [0];console.log (' src: ', img.getattribute (' src '));</Script></Div></Body></HTML>

This more common HTML text contains a node type that we often use. The DOM organizes the HTML document in the form of a node tree, meaning that node is corresponding to the HTML document, even if the line-wrapping in the code is aesthetically pleasing, and is actually reflected in the node tree.

The above HTML corresponds to the nodelist:

The entire document is a file node, which we use a lot more. There are several properties in document with less: URL, domain, referrer, where domain can be set, and this can be used to solve the cross-domain problem between some subdomains. Other special collections, such as forms, images, and links, can be easily manipulated and can also be used to simplify the model when doing crawlers.

There are several commonly used nodes in document type, element, comment, and text.

It is important to note that the difference between the text node and element node is that we usually write the character in the element node, but not that the element contains a character, but that the element node embeds a text node inside it. The contents of the text node are the characters we write in. For example, the structure of <p>papapa</p> should be:

> Line break

Another thing that is often overlooked is the line break. In order to beautify the code, usually we will be wrapped between each label, Dom in parsing the HTML document, the line will also parse the Textnode node! That is, every line of our HTML code comes with a textnode node behind it \n!

> Node Relationships

When it comes to relationships, it's both father-son and sibling relationships. In order to locate a node, we can need several positioning interfaces provided by the DOM: FirstChild, LastChild, PreviousSibling, nextSibling, and ParentNode, ChildNodes. The combination of these interfaces can be used to locate a specific node.

Another thing is nodelist itself, NodeList is a dynamic class array object, dynamic meaning is the DOM changes, the changes will be updated to nodelist, from this nature, nodelist should be a reference set or pointer set. The meaning of an array of classes is that they are not real arrays, but they look a bit like. So when you traverse, you can also use the for-in to iterate through some of the method properties of the object itself, or the normal for I to length, or use foreach, for.

> Node Properties

Each node has corresponding NodeType, nodename, and NodeValue attributes, which are known as the name, and represent the type, name, and value of the node, respectively. To say this, the nodename of the element node is the signature, while the nodevalue is null, and the nodevalue of the text and comment are the corresponding strings.

DOM Operations

Speaking of operation, is nothing more than adding and deleting. In DOM operations, the subject is an element node, so it is essential to operate on element nodes.

    • Check

There are two types of DOM: exact query and traversal query.

1) Accurate query is given a condition to search, there are two main types of interfaces: getelementby*** and queryselector***.

The difference between these two types of queries is real-time and non-real-time. The getelement** method returns the NodeList, so it has real-time nature. While queryselector** returns a snapshot, the changes to the DOM table are not reflected in the query results in real time. Take a look at this example:

<div class= "WRP" > <p>papapa</p></div><script>varDIVs = Document.getelementsbyclassname (' WRP '),//Copy 7 of //var divs = Document.queryselectorall ('. WRP '),//copy of 1I, Div=NULL;  for(i = 0; i < divs.length; i++) {div= Divs[0].clonenode (true);         Document.body.appendChild (DIV); if(I > 5) {              Break; }    }</script>

Using getelements***, the divs is dynamically changing, so it replicates 7 Papapa out of the way. If adopt queryselector*** way, then divs only save the time that state that just query, therefore only will copy a papapa come out. So, if you use GetElement to query, then you need to use a Len variable to save the current state, otherwise it will cause a dead loop. According to our usual cognitive thinking, divs should not change dynamically, after all, I did not continue to query Ah, how can you change it. So, Queryselector way more controllable, will not make some inexplicable bug, and jquery style presumably everyone still like.

2) traversal

The DOM provides 2 traversal iterators: Nodeiterator and Treewalker, and you can, of course, manually implement a traversal.

See the following example for Nodeiterator usage:

1<divclass="WRP">2<p>papapa</p>3<div>4<span>yohohoho</span>5<inputclass= ' input1 ' type= "text"name= "Value=" "/>6</div>7<inputclass="Input2"Type="text"name= "Value=" "/>8</div>9<script>Ten     vardiv =Document. Queryselector ('. WRP '); One     varFilter =function(node) { A         returnNode.tagName.toLowerCase () = = = ' input '? -Nodefilter.filter_accept: -Nodefilter.filter_skip; the} -     varMyiterator =Document. Createnodeiterator (Div, nodefilter.show_element, filter,false); -     varn = Myiterator.nextnode ();//move to root (Div) -      while(N!==NULL) { +Console.log (N.classname); -n = Myiterator.nextnode (); +} A</script>

Treewalker Traversal:

1 vardiv =Document. Queryselector ('. WRP ');2 varFilter =function(node) {3     returnNode.tagName.toLowerCase () = = = ' input '?4Nodefilter.filter_accept:5Nodefilter.filter_skip;6}7 8 varWalker =Document. Createtreewalker (Div, nodefilter.show_element, filter,false);9 varn = walker.firstchild ();Ten  while(N!==NULL) { OneConsole.log (N.classname); An = Walker.nextnode (); -}

Manual way, first talk about the idea: first of all to consider the children there are also children, it is obvious here to use recursive form to do, to determine whether the node has child nodes and recursive. Then there are some details, such as to eliminate the effect of line breaks and text nodes, which of course is to use children directly to get the child nodes. In addition, we need to avoid the dynamic changes of nodelist. Look at the code:

1 functionMywalker (EL, filter, CB) {2     varchildren = El.children;3      for(vari = 0, Len = children.length; i < Len; i++) {4         varWalker = Children[i];5         if(Walker.children.length!== 0) {6Mywalker (Walker, filter, CB);7}Else if(Filter (Walker)) {8CB (Walker);9}Ten} One} A  - vardiv =Document. Queryselector ('. WRP '); -  the functionFilter (node) { -     returnNode.tagName.toLowerCase () = = = ' input '; -} -  + functionCB (node) { -Console.log (Node.classname); +} A  atMywalker (Div, filter, CB);

If you also want to consider the text node, that can use ChildNodes to traverse, this time should pay attention to filter line break.

    • Increase

The add-on interfaces for DOM nodes are: AppendChild () and InsertBefore (). However, creating a node requires two additional interfaces: document.creat*** and Document.clonenode (). After the node is created, the node is placed in the document by adding an interface. In addition to creating normal nodes, you can also create scripts and style sheets, which can be used for load-on-demand, lazy loading, and other resource loading methods. Of course, to make a loader like Requirejs, you need to add a lot of processing logic.

    • By deleting

There are two interfaces removed: ReplaceChild, RemoveChild.

    • Change

1) changes to the content: InnerHTML, innertext,textcontent and the like. Textcontent is generally not used, he is the string that all the text nodes inside the node are stitched together, including line breaks These are also plugged in, so further string processing is required.

2) Change of property

At the beginning of the article, we have already mentioned the two most common methods of changing attributes, namely the Element.props=value and Element.setattribute () series. where GetAttribute () takes the value on the attribute node, which is the string of characters in the angle brackets <> of the HTML tag. Returns a null if it is not defined, and returns a string if one is defined. Element.props is a query of an instance of an HTML tag, which is a query of an instantiated node object. This object, when initialized, will set the undefined attribute in the HTML tag to "" with a definition to parse the transformation. So the same object is queried, An attribute that is not defined. Prop returns a null value and GetAttribute returns NULL, and queries for the style and onload class of event properties that return an object, which returns a string or null, and a query for a custom property that returns a undefined, while the latter returns a custom value.

This is why the results of the two queries are different at the beginning of the article.

> Attributes

The unified management of the various properties in a node is the Attributes property, which is a namednodemap that holds all the properties defined by the object. This is actually an array of classes, here chrome is printed very clearly, at a glance. Remember not to use for in traversal oh.

The corresponding property can be queried in the form of attributes[' id'], which has its own methods, but no one will use it, and attributes the property itself is seldom used. One of the scenarios where it is used (or can be said to be unique) is the centralized management of attributes, or the traversal or bulk initialization, which we usually use basically. Prop form, intuitive and convenient.

> Custom Properties

We can add any custom attribute to the tag, although the freedom is good but the specification is still there. In HTML5, custom attributes are defined in the form of Data-prop. The properties that hang under data can be managed uniformly through the dataset attribute, which can generally be placed on data and then rendered directly by reading the DataSet property, such as knockout, which is also used for data binding.

> Style

A very important aspect of the property is the style, which involves inline styles and style controls for embedding and outreach. As mentioned above, using ELEMENT.STYLT. Styles can change the style directly, or you can read and write all inline styles at once through Element.style.cssText. However, the complexity of the style is embedded, the overlay effect of the outer style, so simply querying the style does not get the final style of the element. This can be done by Document.defaultview's getComputedStyle () method to get the calculation style, just like the chrome developer tool.

However, CSS is a big project, trying to dynamically control the changes of all styles through JS is not reliable. The more common approach is to CSS presets in various states, and JS as a control to control the state of the transformation, that is, control class transformation. In addition to pure classname in DOM programming, the more powerful interface is classlist, which is another class array object. It offers several easy-to-use class management methods: Add, contains, remove, toggle, full of jquery winds. But after all, jquery is a folk woman, when the Orthodox harem absorbed her all kinds of strange techniques, fall out of favour is inevitable.

Summary

Pondering for a long time, but the writing is still a variety of messy, the structure is not clear enough. The structure level of DOM is based on nodelist, and the organic combination of different NodeType nodes forms a DOM table. The DOM operation has a variety of interfaces, it feels a bit confusing, perhaps this is also a variety of frameworks have been working to weaken the developers on the DOM operation, but in the very small-scale application familiar with DOM operation, or more flexible than the use of the framework.

The summary of the DOM is here, looked at the next or finishing the main, the endorsement of Kazakhstan, must fill the map.

Talk about the DOM thing.

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.