Common concept

The composition of JavaScript

The basics of JavaScript are divided into three parts:

  • ECMAScript: A syntax standard for JavaScript. This includes variables, expressions, operators, functions, if statements, for statements, and so on.

  • DOM: Document Object Model, an API for manipulating elements on a web page. Things like moving boxes, changing colors, rotating graphics, etc.

  • BOM: Browser Object Model, an API that operates some functions of the Browser. Like having your browser scroll automatically.

node

Node: The most basic unit of an HTML web page. Each part of a web page can be called a node, such as HTML tags, attributes, text, comments, entire documents, etc.

Although both are nodes, their specific types are actually different. Common nodes are divided into four types:

  • Document node (document) : The entire HTML document. The entire HTML document is a document node.

  • Element node (tag) : HTML tag.

  • Attribute node (attribute) : Attributes of an element.

  • Text node (text) : Text content in HTML tags (including Spaces between tags and line breaks).

Different types of nodes have different attributes and methods. All nodes are objects.

What is the DOM

DOM: Document Object Model. DOM provides a structured representation of a document and defines how to access the document structure through scripts. The goal is to create a specification that allows JS to manipulate HTML elements.

The DOM is made up of nodes.

Parsing process: After the HTML is loaded, the rendering engine generates a DOM tree from the HTML document in memory. GetElementById is used to retrieve the element nodes in the DOM. Then you modify the attributes of that element.

DOM tree :(everything is a node)

The DOM data structure is as follows:

In HTML, everything is a node (very important). The classification of nodes was described in the previous paragraph.

The entire HTML document is a document node. All nodes are objects.

What can DOM do

  • Find the object (element node)

  • Sets the attribute value of the element

  • Sets the style of the element

  • Dynamically create and delete elements

  • Event trigger response: event source, event, event driver

Gets the element node

The way to get a DOM node is actually the way to get an event source. As for the events, they were covered in the last article.

To operate on an element node, you must first find the node. There are three ways to get a DOM node:

var div1 = document.getElementById("box1"); // Get an element node by id. Because id is unique.

var arr1 = document.getElementsByTagName("div"); // Get the element node array by the label name, so there is s

var arr2 = document.getElementsByClassName("hehe"); // Get the element node array by the class name, so there is s
Copy the code

Since methods two and three get the tag array, it is customary to iterate through it before using it.

Special case: Only 1 value in array. Even so, this value is wrapped in an array. This value is obtained as follows:

document.getElementsByTagName("div1") [0];    // Take the first element in the array

document.getElementsByClassName("hehe") [0];  // Take the first element in the array
Copy the code

Get DOM access relationships

The nodes of the DOM are not isolated, so they can be accessed through the relative relationships between DOM nodes. As follows:

Node access relationships exist in the form of attributes.

Visit relationship between father and brother in JS:

The parentNode and children attributes are used as parentNode and children. The following are introduced respectively.

Get the parent node

The caller is the node. A node has only one parent, which is called

Node. ParentNodeCopy the code

Get sibling nodes

1, the next node | the next element nodes:

Sibling is Chinese for brother.

(1) nextSibling:

  • Firefox, Google, IE9+ versions: all refer to the next node (including tabs, empty documents, and line feeds).

  • IE678 version: Indicates the next element node (label).

(2) nextElementSibling:

  • Firefox, Google, IE9+ versions: all refer to the next element node (TAB).

Summary: To get the next element node, we can use nextSibling in IE678 and nextElementSibling in Firefox Google IE9+, so combining these two attributes, we can write:

Next siblings. = node nextElementSibling | | node. NextSiblingCopy the code

2, a node | before an element node:

It’s previous.

(1) previousSibling:

  • Firefox, Google, IE9+ versions: all refer to the previous node (including tabs, empty documents, and line feeds).

  • IE678 version: refers to the previous element node (label).

(2) previousElementSibling:

  • Firefox, Google, IE9+ versions: all refer to the previous element node (tag).

Summary: To get the previous element node, we can use previousSibling in IE678 and previousElementSibling in Firefox After IE9+.

= a brother before node. PreviousElementSibling | | node. PreviousSiblingCopy the code

3. Add: Obtain any sibling node:

Parentnode. children[index];// Get sibling nodes at will
Copy the code

Gets a single child node

1, the first child | the first child node:

(1) firstChild:

  • Firefox, Google, IE9+ versions: all refer to the first child node (including tabs, empty documents, and line feeds).

  • IE678 version: refers to the first child element node (label).

(2) firstElementChild:

  • Firefox, Google, IE9+ versions: all refer to the first child element node (tag).

Summary: to get the firstChild node, we can use firstChild in IE678 and firstElementChild in firefox after IE9+. Combining these two attributes, we can write:

The first child node =. FirstElementChild | | node. FirstChildCopy the code

2, the last child node | the last child node:

(1) lastChild:

  • Firefox, Google, IE9+ versions: All refer to the last child node (including tabs, empty documents, and line feeds).

  • IE678 version: Refers to the last child element node (label).

(2) lastElementChild:

  • Firefox, Google, IE9+ versions: all refer to the last child element node (tag).

Summary: to get the lastChild element node, we can use lastChild in IE678 and lastElementChild in firefox after IE9+. So, combining the two attributes, we can write:

The last child node = node. LastElementChild | | node. LastChildCopy the code

Get all child nodes

(1) childNodes: Standard attribute. Returns a collection of the children of the specified element (including the element node, all attributes, and text nodes). Is the real son of W3C.

  • Advanced versions of Firefox, such as Google, treat newlines as child nodes as well.

Usage:

Array of childNodes = parent nodes. ChildNodes;// Get all nodes.
Copy the code

(2) Children: non-standard attributes. Returns a collection of child element nodes of the specified element. “Important”

  • It only returns HTML nodes, not even text nodes.
  • Comment nodes are included in ie 6/7/8 (in IE678, comment nodes are not written in it).

While not a standard DOM attribute, it is supported by almost all browsers, as is the innerHTML method.

Usage :(most used)

Array of child nodes = parent node. Children;// Get all nodes. Use the most.
Copy the code

DOM node operations (critical)

A node’s access relationships are attributes.

Operations on nodes are functions.

Create a node

The format is as follows:

The new tag (element node) =document.createElement("Label name");
Copy the code

For example, if we want to create a li tag, or an ADBC tag that does not exist, we can do this:

<script type="text/javascript">
    var a1 = document.createElement("li");   // Create a li tag
    var a2 = document.createElement("adbc");   // Create a label that does not exist

    console.log(a1);
    console.log(a2);

    console.log(typeof a1);
    console.log(typeof a2);
</script>
Copy the code

Print result:

Insert the node

There are two ways to insert a node, and they have different meanings.

Method 1:

AppendChild (new child node);Copy the code

A new child node is inserted at the end of the parent node.

Method 2:

Parent node. InsertBefore (new child node, child node for reference)Copy the code

Explanation:

  • Insert a new node before the reference node.
  • If the reference node is null, it inserts a child node at the end of the parent node.

We can see that the Li tag is indeed inserted inside the box1 tag, alongside box2.

Example of mode 2:

As you can see, the B1 TAB is inserted inside the Box1 TAB, alongside the A1 TAB, in front of it.

Lay special emphasis on:

The appendChild method of approach 1 is emphasized here. For example, we now have a div structure like this:

<div class="box11">    <div class="box12">One life,</div></div><div class="box21">    <div class="box22">Never stop</div></div>
Copy the code

In the upper structure, the child box box12 is inside its parent box11, and the child box box22 is inside its parent Box21. Now, if I call the method box11.appendChild(box22), the result is that box22 goes to Box11 (that is, box22 is no longer in box21). This is an amazing thing:

Remove nodes

The format is as follows:

RemoveChild (child node);Copy the code

Delete child node with parent node. You must specify which child node to delete.

If I want to delete my node, I can do this:

	node1.parentNode.removeChild(node1);
Copy the code

Replication node (clone node)

The format is as follows:

The node to copy. CloneNode ();// No arguments in parentheses have the same effect as false. The node to copy. CloneNode (true);
Copy the code

The effect is different with or without arguments in parentheses. The explanation is as follows:

  • No parameter/Parameter false: Only the node itself is copied, not its child nodes.

  • Parameter true: copies both the node itself and all of its children.

Set the properties of a node

We can get node property value, set node property value, delete node property value.

Let’s take the following label as an example:

	<img src="images/1.jpg" class="image-box" title="Pictures of Beautiful Women" alt="Subway At a Glance" id="a1">
Copy the code

The following are introduced respectively.

1. Obtain the attribute value of the node

Method 1:

Element node. Attribute name; Element node [attribute name];Copy the code

Example :(get node attribute value)

<body><img src="images/1.jpg" class="image-box" title="Pictures of Beautiful Women" alt="Subway At a Glance" id="a1"><script type="text/javascript">    var myNode = document.getElementsByTagName("img") [0];    console.log(myNode.src);    console.log(myNode.className);    // Note that className is className, not class console.log(myNode.title); console.log("------------"); console.log(myNode["src"]); console.log(myNode["className"]); Class console.log(myNode["title"]);</script></body>
Copy the code

The img tag in the code above, which has various attributes, can be retrieved one by one, and printed as follows:

Method 2:

Element node.getAttribute ("Attribute Name");
Copy the code

For example:

    console.log(myNode.getAttribute("src"));    console.log(myNode.getAttribute("class"));   // className console.log(myNode.getAttribute("title"));
Copy the code

Print result:

The difference between approach 1 and Approach 2 is that the former manipulates the tag directly, while the latter treats the tag as a DOM node. Recommended Method 2.

2. Set the node properties

Mode 1 example :(setting node attributes)

    myNode.src = "images/2.jpg"   // change SRC attribute value myNode.className = "image2-box"; // Change the class name
Copy the code

Method 2:

Element node.setAttribute ("Attribute name"."New property value");
Copy the code

Mode 2 example :(setting node attributes)

    myNode.setAttribute("src"."images/3.jpg");    myNode.setAttribute("class"."image3-box");    myNode.setAttribute("id"."Hello");
Copy the code

3. Delete node attributes

Format:

Element node. RemoveAttribute;Copy the code

Example :(deleting node attributes)

    myNode.removeAttribute("class");    myNode.removeAttribute("id");
Copy the code

conclusion

There are two ways to get the property value of a node and to set the property value of a node.

For primitive attributes of nodes (such as the class/className attribute, style attribute, title attribute, SRC attribute of img tag, href attribute of hyperlink, etc.), mode 1 and mode 2 are equivalent and can be mixed. How do you make sense of mixing? For example, div. Title = ‘I am the title’ to set the attribute and div. GetAttribute (‘title’) to get the attribute are mixed.

But if it is a “non-original property” of the node, for example:

div.aaa = 'qianguyihao'; div.setAttribute('bbb'.'qianguyihao');
Copy the code

The “non-primitive property” above is different when used in these two ways. The differences are as follows:

  • Element node of mode 1. Attribute and element node [attribute] : Binding attribute values do not appear on the tag.

  • Get /set/removeAttribut: The bound attribute value appears on the tag.

  • The two methods cannot be used interchangeably; get and set values must use the same method.

For example:

<body><div id="box" title="The body" class="asdfasdfadsfd">I love you China</div><script>    var div = document.getElementById("box");    // set div.aaaa = "1111"; console.log(div.aaaa); // Prints 1111. // Set div.setattribute (" BBBB ","2222"); // BBBB will appear on the tag console.log(div.getAttribute("aaaa")); // Prints the result: null. Method 2 cannot get because method 1 is set. console.log(div.bbbb); // Print result: undefined. Method 1 cannot get because method 2 is set.</script></body>
Copy the code

DOM object properties – Added

InnerHTML vs. innerText

  • Value: indicates the value attribute of the label.

  • InnerHTML: The contents of the double-closed tag (containing the tag).

  • InnerText: The contents of the double-closed tag (excluding the tag). (Older versions of Firefox used textContent.)

Get content examples:

If we want to get the contents of innerHTML and innerText, see what happens :(the innerHTML gets the tag itself, but the innerText doesn’t)

Example :(innerHTML modifies the tag itself, but innerText does not)

NodeType property

Here’s the nodeType attribute.

  • NodeType == 1 represents the element node (label). Remember: In this case, elements are tags.

  • NodeType == 2 indicates that the node is an attribute node.

  • NodeType == 3 is a text node.

NodeType, nodeName, nodeValue

Let’s take the following tag for example:

<div id="box" value="111">One life,</div>
Copy the code

The label above contains three types of nodes:

  • Element node (tag)

  • An attribute node

  • Text node

The three nodes can be obtained as follows:

    var element = document.getElementById("box1");  Var attribute = element.getAttributenode ("id"); Var TXT = element.firstChild; // Get the text node of box1 var value = element.getAttribute("id"); Console. log(element); console.log("--------------"); console.log(attribute); console.log("--------------"); console.log(txt); console.log("--------------"); console.log(value);
Copy the code

The print result is as follows:

Since these three are all nodes, if I want to get their nodeType, nodeName, and nodeValue, the code is as follows:

    var element = document.getElementById("box1");  Var attribute = element.getAttributenode ("id"); Var TXT = element.firstChild; // Get the text node of box1 // get nodeType console.log(element.nodetype); //1 console.log(attribute.nodeType); //2 console.log(txt.nodeType); //3 console.log("--------------"); // Get nodeName console.log(element.nodename); //DIV console.log(attribute.nodeName); //id console.log(txt.nodeName); //#text console.log("--------------"); // get nodeValue console.log(element.nodevalue); //null console.log(attribute.nodeValue); //box1 console.log(txt.nodeValue); // Life One
Copy the code

The print result is as follows:

Document loading

When a browser loads a page, it loads it from top to bottom, running it as it reads it. If the script tag is written to the top of the page, the page is not loaded when the code is executed, and the DOM object is not loaded or loaded, the DOM object cannot be obtained.

The onload event:

The onload event is triggered after the entire page has loaded. Bind an onload event to the window, and the corresponding response function will be executed after the page is loaded, ensuring that all DOM objects are loaded by the time our code executes.

Code examples:

<! DOCTYPEhtml><html>  <head>    <meta charset="UTF-8" />    <title></title>    <script type="text/javascript">      // This js code is written in the  tag, so it is recommended to put it in the window.onload. Window.onload = function() {var BTN = document.getelementById (" BTN "); Btn.onclick = function() {alert("hello"); }; };</script>  </head>  <body>    <button id="btn">Point me</button>    <script type="text/javascript">      // This js code is written in the  tag, the position of the code is at the bottom of the page. Doing so also ensures that the JS code is executed after the page has loaded. Var BTN = document.getelementById (" BTN "); Btn.onclick = function() {alert("hello"); };</script>  </body></html>
Copy the code

In the above code, both methods 1 and 2 ensure that the js code is executed after the page is loaded.

My official account

Want to learn skills beyond code? Might as well pay attention to my wechat public number: front-end Ozawa