Detailed Explanation and Example Code of javascript DOM

  • 2021-07-26 06:36:42
  • OfStack

javascript DOM Summary

I think DOM (Document Object Model) is the simplest part of JS. Undeniably, it is really simple, because DOM's thinking mode is a bit fixed, and it only needs to remember some fixed methods, so DOM can be said to be the starting point for all js (here referring to the client's js).

Recently, when I was doing some exercises that used DOM, I found that my knowledge of DOM was very scattered (1 thought I had mastered it very well). Many friends may think that DOM means calling several methods, or I can use jQuery directly without considering the details of DOM at all. Yes, that's right. jQuery has unprecedented encapsulation of DOM, but just like growing 1, 1 must walk before running, so I think we must have a more detailed understanding of DOM, so I summarized the following 1 usage methods of DOM.

In the W3C summary of DOM specification, there are some 10 points commonly used and some not very useful. Here we mainly discuss some commonly used DOM operations (the basic concepts of DOM will not be introduced here):

Node hierarchy

The so-called node hierarchy refers to the existence of nodes (such as tags) with their own characteristics, data and methods in html documents, and the relationship between nodes constitutes a hierarchy (in fact, it can be imagined as a tree structure). An NODE interface is defined in the DOM1 level specification of W3C. There are 1 methods of this interface that are very useful:

Node. ELEMENT_NODE; (Element Node)

Node.TEXT_NODE; (Text Node)

Node. DOCUMENT_NODE (Document Node)

Each node has its own node type flag, that is, NodeType attribute, such as nodeType = = '1' for element nodes; nodeType = = '3' for text nodes; nodeType = = '9' for the document node;

1. Document Node

The document node is represented in a document as an document object, and its basic characteristics are as follows:


console.log(document.nodeType); // 9 
console.log(document.nodeName); // #document 
console.log(document.nodeValue); // null 
console.log(document.parentNode); // null( It is already the topmost node, the root node of the tree ) 

tip one (child node of document):

1. document. documentElement can fetch html objects, which can also be fetched through document. childNodes [0] and document. firstchild. However, documentElement can access elements faster and more directly.

tip two (documentation information):

1. Get the document title: document. title;

2. Obtain complete url: document. URL;

3. Obtain the domain name (ip): document. domain;

4. Get the page's URL: document. referrer;

tip three (document lookup element):

1. Adopt id: document. getElementById ("xxx"); 1 page id will be different, if there are more than one identical id, the first element with the id will be fetched.

2. Adopt tagName: document. getElementsByTagName ("xxx"); Returns the collection of elements with the label name "xxx"!

3. Adopt name: document. getElementByName ();

Understanding document objects is very simple, and compatibility is relatively high.

2. Element nodes

Element nodes provide access to element tag names, child nodes, and attributes. Its basic characteristics are as follows:


var ele = document.getElementById("element"); // Pass document Get 1 Label objects  
console.log(ele.nodeType); // 1 
console.log(ele.nodeName); //  Returns the label name of the element  
console.log(ele.nodeValue); // Return forever null! 

tip one (html element):

     < div id="myDiv" class="bd" title="Body text" lang="en" dir="ltr" > < /div >

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

1. console. log (div. id); //"myDiv"

2. console. log (div. className); //"bd"

3. console. log (div. title); //"Body text"

4. console. log (div. lang); //"en"

5. console. log (div. dir); //"ltr"

tip two (Get, Set, and Remove Features):

1. div. getAttribute ("id"); //"myDiv"

2. div. setAttribuye ("id", "yourDiv"); //id changed

3. div. removeAttribute ("id"); //id deleted

Note: In IE 7 and later, there are some abnormal behaviors in the three methods. Setting class and style features through set, especially event handlers, has no effect, and get is the same. Therefore, the above three methods should be avoided in general development, and it is recommended to set characteristics through attributes.

tip three (child node of element):

Here is the key point to mention 1. There are the following codes:


<ul id="myList"> 
  <li>Item 1</li> 
  <li>Item 2</li> 
  <li>Item 3</li> 
</ul> 
 
var mL = document.getElementById("myList"); 
// It's obvious mL Objects are 3 Element nodes, we also know how to use childNodes Property to find the number of nodes, but a trap follows  
 
console.log(mL.childNodes); // 7 
//?! How can there be 7 A ? 
 
// The reason is that childNodes Contains not only element nodes, but also 4 Text nodes. Therefore, it needs to be filtered  
 
for(var i=0,len=ml.childNodes.length;i<len;i++){ 
   if(ml.childNodes[i].nodeType == "1"){ //  Take advantage of the characteristics of element nodes  
     // .... 
   }   
}<br>// The best way to do this <br>// If the internal label name of the element object is 1 Like <br>var items = ml.getElementsByTagName("li"); // Available 3 A li Node object  
    

3. Text nodes

Text nodes contain plain text that can be interpreted literally. Plain text can contain escaped HTML characters, but not HTML codes. The basic characteristics of text nodes are as follows:


<div id="myDiv">123</div> 
 
var myDiv = document.getElementById("myDiv") // Get the element node  
var tx = myDiv.childNodes[0] // As mentioned earlier childNodes The feature of, this time the text node is taken  
 
console.log(tx.nodeType) // 3 
console.log(tx.nodeName) //  Of all text nodes nodeName It's all "#text"; 
console.log(tx.nodeValue) // 123( Text contained by the node ) Note that an element node cannot fetch the text of the text node it contains  
 
// So its parent node is obviously an element node . 

Tip one:

Two ways to create text nodes: document. createTextNode (), document. createText ();

After being created, it will not be directly embedded in the document, and it needs to be referenced.


var a = document.createElement("p");

      var b = document.createTextNode("123");

      a.appendChild(b);

      document.body.appendChild(a);

This will appear at the end of body < p > 123 < /p > Such a label

Personally, I think DOM is definitely the entry point for learning js, but it also needs a long time to polish. I have read DOM no less than 3 times, only DOM1 level specification, and every time there is something new. If you study DOM, you should pay attention to some pitfalls and spend more time thinking about them.  

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: