JavaScript-05 DOM Programming The most detailed, comprehensive and understandable in the whole network

The DOM written this time is all written in one article, but it is still very detailed! If there is anything you don’t understand, you can write it in the comment area below

Directory

1. Basic introduction to DOM

1.1 What is DOM

1.2 DOM tree (family tree)

2. Basic attributes and methods

2.1 Properties

2.2 Method

3. Find HTML DOM elements

2.1 getElementById()

2.2. getElementsByTagName()

2.3 getElementsByClassName()

4. Change HTML elements (content)

Five. DOM node operation introduction

5.1 Node overview

5.2 The role of nodes

5.3 Node Hierarchy

5.3.1 Parent node [node.parentNode]

5.3.2 Child nodes [parentNode.childNodes (standard)]

5.3.3 Brother nodes

5.4 Node operation

5.4.1 Creating Nodes

5.4.2 Adding Nodes

5.4.3 Delete Node

5.4.4 Duplicate Node (Clone Node)

Six. Case

picture switching


1. Basic introduction to DOM

1.1 What is DOM

Document Object Model (
Document Object Model
, referred to as
DOM
),yes
W3C
Organization Recommended for Processing Extensible Markup Language

(
HTML
or
XML
)of
Standard programming interface
.

W3C
has defined a series of
DOM
interface, through these
DOM
Interfaces can change the content, structure, and style of a web page.

1.2 DOM tree (family tree)

When a web page is loaded, the browser creates the page’s Document Object Model (
Document Object Model
),
HTML DOM
Model

is structured as a tree of objects:

HTML DOM is HTML’s standard object model and programming interface. which defines:

  • HTML elements as objects
  • Attributes of all HTML elements
  • Method to access all HTML elements
  • Events for all HTML elements

Document: A page is a document, which is represented by document in DOM

Element: All tags in the page are elements, which are represented by element in DOM

Node: All content in a web page is a node (label, attribute, text, comment, etc.), which is represented by node in DOM

Note: DOM regards the above content as objects

2. Basic attributes and methods

2.1 Attributes

  • nodeName: Returnsthe name of the node, depending on its type.
  • nodeType: Returnsthe type of the node.
  • attributes: Returns the attributes of the element.
  • childNodes: Returns a NodeList of the element’s child nodes.
  • firstChild: Returns the first child of the element.
  • lastChild: Returns the last child node of an element.
  • parentNode: Returns the parent node of the element.
  • nextSibling: Returns the next node after the element.
  • previousSibling: Returns the node that immediately precedes the element.
  • textContent: Sets or returns the text content of the element and its descendants.
  • innerTest: Sets or returns the text content of the element’s descendants.
  • innerHTML: Sets or returns the content of the element’s descendants.

2.2 Method

  • hasAttribute(name): Returns whether the elementhas the specified attribute.
  • hasAttributes(): Returns whether the elementhas attributes.
  • hasChildNodes(): Returns whether the elementhas child nodes.
  • createAttribute(node):Create an attribute node.
  • createElement(node): Creates a element node.
  • createTextNode(node): Creates a text node.
  • appendChild(node): Adds a new child node to the end of the node’s child node list.
  • cloneNode(include_all:true,false):Clone the node.
  • removeAttribute(name):Remove the specified attribute.
  • removeChild(node):Remove a child node.
  • replaceNode(newNode):Replaces a node. [IE only]
  • replaceChild(newNode, oldNode):Replace child nodes.
  • getElementById(id): Finds the descendant element with the specified id. [HTML DOM]
  • getElementsByName(name): Findschildren elements with the specified name. [HTML DOM]
  • getElementsByTagName(name): Finds elements that are descendants of the specified tag name.
  • getAttribute(name): Returns the value of an attribute.
  • setAttribute():Adds a new attribute.

3. Find HTML DOM elements

HTML DOM can be accessed through JavaScript (and other programming languages as well). In the DOM, all HTML elements are defined as objects. We can manipulate these objects through JavaScript to change the content of HTML elements.

2.1 getElementById()

Use the getElementByID() method to get the element object with ID

<div id="oDiv">You were awesome today! </div>
<script type="text/javascript">
var oDiv = document. getElementById('oDiv');
console. log(oDiv)
</script>

2.2. getElementsByTagName()

Use the getElementsByTagName() method to return a collection of objects with the specified tag name.

document.getElementsByTagName('tag name')

Notes:

  • Because what you get is a collection of objects, you need to traverse if you want to operate the elements inside
  • Get element object is dynamic

You can also get all the child elements of the specified tag inside an element (parent element).

element.getElementsByTagName('tag name');

Note: The parent element must be a single object (the object of which element must be specified). The parent element itself is not included when getting it.

2.3 getElementsByClassName()

getElementsByName() method returns a collection of objects with the specified name.

This method is similar to the getElementById() method, but it queries the element’s name attribute instead of the id attribute.

Also, because the name attribute may not be unique within a document (e.g. radio buttons in an HTML form usually have the same name attribute

), all getElementsByName() methods return an array of elements, not a single element.

Demo example:

function s_input(){
  var aInput=document. getElementsByName("season");
  var sStr="";
  for(var i=0;i<aInput. length;i ++ ){
sStr + =aInput[i].value + "<br />";
}
document.getElementById("s").innerHTML=sStr;
}

Four. Change HTML elements (content)

method

Description
element.innerHTML=new HTML content Change HTML content of the element
element.innerTEXT = new text Change the text content of the element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(< em>attribute, value) Change the attribute of the HTML element Value
element.hasAttribute(attribute) Determine whether the element has this attribute
element.removeAttribute(attribute) Delete element attribute
element.style.property = new style Change the style of HTML elements

5. DOM node operation introduction

5.1 Node Overview

  • All content in a web page is a node (label, attribute, text, comment, etc.), and in the DOM, a node is represented by Node.

  • All nodes in the HTML DOM tree can be accessed through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

Generally, a node has at least three basic attributes: nodeType (node type), nodeName (node name) and nodeValue (node value).

  • Element node nodeType is 1

  • attribute node nodeType is 2

  • The nodeType of the text node is 3 (the text node contains text, spaces, newlines, etc.)

[Summary] In our actual development, node operations mainly operate on “element nodes”.

5.2 The role of nodes

Get page elements.

  • Use the methods provided by DOM to get elements

    • document. getElementById()

    • document. getElementsByTagName()

    • document.querSelector, etc.

    • Lack of logic and cumbersome

  • Using node hierarchy to get elements

    • Use parent-child sibling node relationship to get elements

    • Strong logic, but poor compatibility

5.3 Node level

5.3.1 Parent node [node.parentNode]

The DOM tree can be used to divide nodes into different hierarchical relationships, the common one is the parent-child-brother hierarchical relationship

  • The parentNode attribute can return the parent node of a node, pay attention to the nearest parent node

  • Returns null if the specified node has no parent

5.3.2 Child Node [parentNode.childNodes (Standard)]

parentNode.childNodes returns a collection of child nodes including the specified node, this collection is an instant update collection

Note: The return value includes all child nodes, including element nodes, text nodes, etc.

If you want to get the element nodes inside, you need to deal with it specially, so we generally don’t advocate the use of childNodes

var ul = document. querySelector('ul');
for(var i = 0; i < ul. childNodes. length; i ++ ) {
if(ul. childNodes[i]. nodeType == 1) {
//ul.childNodes[i] is the element node
console.log(ul.childNodes[i]);
}
}

5.3.3 Brother Node

node. nextSibling

nextSibling returns the next sibling node of the current element, and returns null if it cannot be found. Similarly, it also includes all nodes

node. previousSibling

previousSiblin returns the previous sibling node of the current element, and returns null if it cannot be found. Similarly, it also includes all nodes

specific element node

node.nextElementSibling

nextElementSibling returns the next sibling element node of the current element, if not found, returns null

node. previousElementSibling

previousElementSibling returns the previous sibling node of the current element and returns null if it cannot be found

5.4 Node operations

5.4.1 Create a node

document. createElement(‘tagName’)

The document.createElement() method creates the HTML element specified by tagName. Because these elements did not exist originally and were dynamically generated according to our needs, we also call it dynamically create element nodes

5.4.2 Adding nodes

node.appendChild(child)

The node.appendChild() method appends a node to the end of the list of children of the specified parent node. Similar to the after pseudo-element in css

// 2. Add node node.appendChild(child) node parent child child
// Append elements later, similar to push in an array
var ul = document. querySelector('ul');
ul.appendChild(li);

// 3. Add node node.insertBefore(child, specified element);
var lili = document. createElement('li');
ul.insertBefore(lili,ul.children[0]);

5.4.3 Delete node

node. removeCjild(child)

The node.removeChild() method removes a child node from the DOM and returns the removed node

// 1. Get the element
var ul = document. querySelector('ul');
// 2. Delete element node.removeChild(child);
ul. removeChild(ul. children[0]);

5.4.4 Copy node (clone node)

node. cloneNode()

The node.cloneNode() method returns a copy of the node on which it was called. Also known as clone node/copy node

Notice:

  • If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the copied node itself is cloned, and the child nodes inside are not cloned

  • If the parenthesis parameter is true, it is a deep copy, which will copy the node itself and all its child nodes

node.cloneNode(); //Shallow copy, do not copy content, only copy tags
node.cloneNode(true); //deep copy, copy content, copy label

6. Case

Image toggle

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image switching</title>
<script type="text/javascript">
//Array definition to save the names of all pictures
var images = [
"img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
"img/5.jpg"];
\t\t
var index = 0;
\t\t\t
// Declare a variable to hold the timer
var timer = null;
\t\t
\t\t\t
\t\t
\t\t
\t\t
//load function
window.onload = function(){
\t\t\t\t
// Get the image tag and call src to reassign
var oImg = document. querySelector("img");
\t\t\t\t
\t\t\t\t
\t\t\t\t
\t\t\t\t
//Encapsulate a function to save the next code
function next(){
index + + ;
if(index >= images. length){
index = 0;//return to 0
}
oImg.src = images[index];//0 1 2 3 4
console. log(index);
}
\t\t\t\t
\t\t\t\t
\t\t\t\t
\t\t\t\t
//Manually click on the next one to switch
var nextBtn = document. getElementById("nextBtn");
//Set click event
nextBtn.onclick = function(){
next();
};
\t\t\t\t
//Manually click on the previous one to switch
var backBtn = document. getElementById("backBtn");
//Set click event
backBtn.onclick = function(){
index--;
if(index < 0){
index = images.length-1;//return to 0
}
oImg.src = images[index];//0 1 2 3 4
console. log(index);
};
\t\t\t\t
\t\t\t\t
// button for automatic switching
var autoBtn = document. getElementById("autoBtn");
autoBtn.onclick = function(){
window.clearInterval(timer);
//set timer
timer = window.setInterval(function(){
next();
},2000);
};
\t\t\t\t
var closeBtn = document. getElementById("closeBtn");
closeBtn.onclick = function(){
window.clearInterval(timer);
}
};
\t\t\t
\t\t\t
</script>
</head>
<body>
<!-- call src attribute object.attribute -->
<img src="img/1.jpg" alt="" width="300" height="300">
\t\t
<button id = "backBtn">Previous</button>
<button id="nextBtn">Next</button>
<button id="autoBtn">Automatically switch pictures</button>
<button id="closeBtn">Close switching pictures</button>
\t\t
</body>
</html>
syntaxbug.com © 2021 All Rights Reserved.