The DOM is introduced
1. Documentation: “D” in DOM
DOM is an acronym for Document Object Model. Without a document, DOM would be a dead end. DOM comes into being behind the scenes when you create a web page and load it into a Web browser. It will create a document object based on the web document you wrote.
In our own language, the word “object” tends to have a less definite and specific meaning. It can refer to almost anything that exists objectively. But in programming languages, the word “object” is very specific and specific.
2. Object: “O” in DOM
An object is an independent collection of data. The variables associated with a particular object are called properties of that object; The functions that can be called from a particular object are called the methods of that object.
Objects in the Javascript language can be divided into three types:
- User-defined objects: Objects created by programmers.
- Native objects: objects in the built-in Javascript language, such as Array, Math, and Date.
- Host Object: An object provided by the browser, such as the Window object
3. Model: “M” in DOM
The “M” in DOM stands for “Model,” but it’s safe to say it stands for “Map.” A model, a map, is a representation of something. Just as a model train represents a real train and a city street map represents a century-old city, the DOM represents the current web page loaded into a browser window: the browser provides the current map (or model), which we can read in JavaScript.
Since it is a map, there must be signs such as directions, contours and scales. In order to understand and use a map, you need to know the meaning and purpose of this notation — the same goes for DOM. To get information from the DOM, we must first understand the various notations used to represent and describe a document.
DOM’s representation of a document as a tree (” tree “is a mathematical concept here) is key to our understanding and application of this model. More specifically, DOM represents a document as a family tree.
The family tree number itself is a model. A family tree is typically used to represent the lineage of a human family and to indicate the relationships between family members using notations such as parent, child, and sibling. A family tree can concisely represent some rather complex relationships: a particular member is the father of some, the son of another, and the brother of another.
Similar to the human family tree, the family tree model is also useful for representing a document written in HTML.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>class list</title>
</head>
<body>
<h2>What course are you buying?</h2>
<p title='Please select the course to purchase'>This course is web full stack course, look forward to your purchase!</p>
<ul id='classList'>
<li class='item'>JavaScript</li>
<li class='item'>css</li>
<li>DOM</li>
</ul>
</body>
</html>
Copy the code
With this figure you can see that the family tree number HTML is the root element. There is no doubt that HTML elements are perfectly representative of the entire document.
We’ll find two branches: and . They exist on the same plane and do not contain each other, so they are brothers. They have a common parent < HTML >, but each has its own child, so they are themselves the parent of some other element.
The element consists of two child elements:
and
,
, and
-
(the three elements are siblings). If we drill down, we’ll see that
- elements.
-
is also a parent element. He has three child elements, all of which are
With this simple notation of family tree relations, we can express the relationship between the elements in a concise and clear way.
If we think of the various document elements as nodes in a family tree, we can use the same notation to describe the DOM. However, it is more accurate to call a document a “tree of nodes” than to use the term “family tree.”
node
The term node comes from network theory. It represents a point of connection in a network. A network is a collection of nodes.
In the real world, everything is made of atoms. Atoms are nodes of reality. But the atoms themselves can be further broken down into even smaller subatomic particles. These subatomic particles are also nodes.
The same is true for DOM. A document is also a collection of nodes, but in this case the nodes are branches and leaves on the document tree.
There are many different types of nodes in the DOM. Just as atoms contain subatomic particles, some DOM nodes contain other types of nodes.
1. Element nodes
In the course list document above, elements like ,
,
-
are called element nodes. If a document on the Web is a building, the elements are the building blocks, and the layout of the elements within the document forms the structure of the document.
The various tags provide the name of the element. The text paragraph element is named “P”, the unordered list element is named “ul”, and the list item element is named “Li”
2. Text nodes
An element is just one of the different node types. If a document consists entirely of blank elements, it will have a structure, but the document itself will contain nothing. On the Web, content is everything. Documents without content are worthless, and most content is provided by text.
This course is web full stack course, looking forward to your purchase! < / p >. The
element contains the text “This course is a full stack web course, looking forward to your purchase!” . It’s a text node.
3. Attribute node
There are other node types as well. For example, annotations are another node type. But here we are talking about attribute nodes.
Elements have more or less attributes that describe them more specifically. For example, almost all elements have a title attribute, which we can use to describe exactly what is contained within the element:
<p title='Please select the course to purchase'>This course is web full stack course, look forward to your purchase!</p>
Copy the code
In the DOM, title=’ Please select the course to purchase ‘is an attribute node. As shown in the figure. Because attributes are always placed in the start tag, the attribute node is always included in the element node. Not all attributes are contained within the element, but all attributes are contained within the element.
How to get an element node
1. The getElementById () method
DOM provides a method called getElemntById(), which returns an object corresponding to the element node with the given ID attribute value. This method is the function associated with the Document object. The getElemntById() method takes only one argument: the id attribute value of the element you want. The ID value must be a string.
Grammar:
document.getElementById(id)
Copy the code
Example:
var oUl = document.getElementById('classList');
Copy the code
This call returns an object that corresponds to a unique element in the Docuemnt object whose HTML ID attribute value is classList.
console.log(typeof oUl);//object
Copy the code
** Each element in the document corresponds to an object. ** Using methods provided by DOM, we can filter out any object corresponding to these elements.
2. The getElementsByTagName () method
This method returns a collection of element objects.
Grammar:
document.getElementsByTagName(localName: DOMString)
Copy the code
Example:
var listItems = document.getElementsByTagName('li')
Copy the code
Results:
Each element in this collection is an object. We can get the length of the current collection by listitems.length, and iterate through the element object of each item through the for loop.
Note that the getElementsByTagName() method returns a collection of elements even if only one element in the entire document has a given tag name. In this case, it has length 1.
3. The getElementsByClassName () method
We will have the same or more Li tags when building a web page, and it will be more efficient if we use getElementsByTagName() to get the filter again. In the same way that we used class to categorize certain elements,DOM also provides a method to get certain DOM element objects by class name, getElementBysClassName().
Grammar:
document.getElementsByClassName(classNames: DOMString)
Copy the code
Example:
var classItems = document.getElementsByClassName('item');
Copy the code
Results:
Thus, it is also a collection of element objects. Only part of the element object is retrieved after the class name is set.
Come on, you can do it
We can use the above three methods to find the corresponding element. After finding the element, we can use the getAttribute() and setAttribute() methods to operate on the attribute value of the element
1. GetAttrbute () method
The getAttribute() method takes only one parameter — the name of the property you intend to query.
Grammar:
object.getAttribute(attributeName: DOMString)
Copy the code
For example, in the example above, how do I print out the title property in the P tag?
var oP = document.getElementsByTagName('p') [0];
var title = oP.getAttribute('title');
console.log(title);
Copy the code
Results:
If no result is found, the call returns NULL, which is a null value in JavaScript that says, ‘This thing doesn’t exist.’
2. The setAttribute () method
The setAttrbute() method allows us to modify the value of the attribute node. This method passes two arguments. The first parameter is the attribute name and the second parameter is the attribute value
Grammar:
object.setAttribute(attribute,value)
Copy the code
Such as:
var classList = document.getElementById('classList');
classList.setAttribute('title'.'This is our latest course.');
Copy the code
Effect:
In the same way, we can modify the title attribute of the above p tag by using the setAttribute() method.
One detail worth noting here is that changes made to the document using the setAttribute() method are still the same attribute values if we look at the source code — that is, changes made by the setAttribute() method are not reflected in the source code of the document itself. This duplicity stems from the WAY the DOM works: ** loads the static contents of a document and then refreshes them dynamically, without affecting the static contents of the document. ** This is where the real power and allure of the DOM comes in: refreshing the content of the page does not require the end user to perform a page refresh in their browser.
Node properties
In the Document Object Model (DOM), each node is an object. DOM nodes have three important properties:
- NodeName: indicates the nodeName
- NodeValue: specifies the nodeValue
- NodeType: nodeType
1. The nodeName property is the name of the node, which is read-only
- The nodeName of the element node is the same as the label name
- The nodeName of the property node is the same as the name of the property
- The nodeName of a text node is always #text
- The nodeName of the document node is always #document
2. NodeValue: specifies the nodeValue
-
The nodeValue of the element node is undefined or null
-
The nodeValue of a text node is the text itself
-
The nodeValue of an attribute node is the value of the attribute
3. The nodeType property: Type of node, which is read-only.
There are several common node types:
The element type | The node type |
---|---|
The element | 1 |
attribute | 2 |
The text | 3 |
annotation | 8 |
The document | 9 |
validation
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node properties</title>
</head>
<body>
<div id="box">I'm a text node<! -- I am a comment --></div>
<script type="text/javascript">
// 1. Get the element node
var divNode = document.getElementById('box');
console.log(divNode.nodeName + '|' + divNode.nodeValue + "/" + divNode.nodeType);
// 2. Get the properties node
var attrNode = divNode.attributes[0];
console.log(attrNode.nodeName + '|' + attrNode.nodeValue + "/" + attrNode.nodeType);
// 3. Get the text node
var textNode = divNode.childNodes[0];
console.log(textNode.nodeName + '|' + textNode.nodeValue + "/" + textNode.nodeType);
// 4. Get the comment node
var commentNode = divNode.childNodes[1];
console.log(commentNode.nodeName + '|' + commentNode.nodeValue + "/" + commentNode.nodeType);
// 5. Document node
console.log(document.nodeName + '|' + document.nodeValue + "/" + document.nodeType);
</script>
</body>
</html>
Copy the code
attributes
Properties are the collection of all properties retrieved from the node objectchildNodes
Property is the collection of all children of the node object
Effect display:
.childnodes attribute
Returns a list of all children of the selected element node, which can be viewed as an array with the length attribute.
Grammar:
elementNode.childNodes
Copy the code
Note:
If the selected node has no child nodes, this property returns the NodeList that does not contain the node
FirstChild properties
The firstChild property returns the firstChild in the childNodes array. This property returns NULL if the selected node has no children.
Grammar:
node.firstChild
Copy the code
Has the same effect as elementNode.childNodes[0]
LastChild properties
The lastChild property returns the lastChild in the childNodes array. This property returns NULL if the selected node has no children.
Grammar:
node.lastChild
Copy the code
With elementNode..childnodes [elementNode..childnodes. Length – 1) is the same effect
ParentNode properties
1. Obtain the parent node of the specified node
Grammar:
elementNode.parentNode
Copy the code
Note: There can only be one parent node
2. Access the ancestor node
elementNode.parentNode.parentNode
Copy the code
3. Access the sibling node
The nextSiblings property returns the node immediately after a node, or null if there is no node
Grammar:
nodeObject.nextSibling
Copy the code
The previousSibling() attribute returns the node immediately preceding the node, or null if there is none
Grammar:
nodeObject.previousSibling
Copy the code
In both cases, Google browser yields blank text nodes (for example, newlines).
Problem solving method
Check whether the nodeType of the node is 1. If the node is an element node, skip
function get_nextSibling(n){
var x = n.nextSibling;
while(x && x.nodeType! =1){
x = x.nextSibling;
}
return x;
}
var paraNode = document.getElementById('p1');
console.log(get_nextSibling(paraNode).nodeName);//UL
Copy the code
Node method
Create node createElement()
The createElement() method creates an element node. This method returns an Element object
Grammar:
var newNode = document.createElement(tagName);
Copy the code
Parameters:
TagName: Character pass value. This string is used to specify the type of element to be created
Example:
var newNode = document.createElement('p');
console.log(newNode.nodeName);//P
Copy the code
Just creating a new p element node, how do you set the text content of the tag?
Note: This text content, the P tag can be either plain text, or it can contain some other tag text within the P tag.
The innerText attribute
Get or set the text only on the element
newNode.innerText = 'mjj';
console.log(newNode);//<p>mjj</p>
Copy the code
If you insert a MJJ in the P tag, you’ll find that MJJ is also set as text.
InnerHTML attribute
You can set both text and labels
newNode.innerHTML = '<a>mjj</a>'
Copy the code
Note: If you want to get the text content of a node object, you can call the innerText or innerHTML property to get it
How do WE insert the new node object we created into the node location we specified? Next to know
Insert node appendChild()
Adds a new child node after the last child node of the specified node
Grammar:
appendChild(newNode);
Copy the code
Parameters:
NewNode: specifies the node to be added
Insert node insertBefore()
The insertBefore() method inserts a new child before an existing one
Grammar:
insertBefore(newNode,node);
Copy the code
Parameters:
NewNode: indicates the newNode to be inserted
Node: specifies the node to be inserted before this node
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Method of nodes</title>
</head>
<body>
<div id="box">
<p>html</p>
</div>
<script type="text/javascript">
var oBox = document.getElementById('box');
var newNode = document.createElement('p');
newNode.innerHTML= '<a>JavaScript</a>';
oBox.insertBefore(newNode2,newNode);
// equivalent to obox.insertbefore (newNode2, obox.firstchild);
</script>
</body>
</html>
Copy the code
RemoveChild ()
The removeChild() method removes a node from the child node list. This method returns the deleted node on success or NULL on failure
Grammar:
nodeObject.removeChild(node);
Copy the code
Parameters:
Node: Required, specifying the node to be removed
Example:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Method of nodes</title>
</head>
<body>
<div id="box"><p>html</p></div>
<script type="text/javascript">
var oBox = document.getElementById('box');
var x = oBox.removeChild(oBox.childNodes[0]);
console.log(x);
</script>
</body>
</html>
Copy the code
Note: The deleted child node is assigned to x, which is not in the DOM tree but still exists in memory. The object can be deleted by x =null.
5. Replace element node replaceChild()
ReplaceChild implements child node (object) replacement. Returns a reference to the replaced object
Grammar:
node.replaceChild(newnode,oldnew);
Copy the code
Parameters:
Newnode: Required, the object used to replace oldNew
Oldnew: Required, object replaced by newNode
Example:
var oldnew = document.getElementById('text');
var newNode = document.createElement('p');
newNode.innerHTML = 'Vue';
oldnew.parentNode.replaceChild(newNode,oldnew);
Copy the code
6. CreateTextNode createTextNode
The createTextNode() method creates a new Text node and returns the newly created Text node
Grammar:
document.createTextNode(data);
Copy the code
Parameters:
Data: string value that specifies the text of this node
Example: Create a div and add a message to it
var newNode = document.createElement('div');
var textNode = document.createTextNode('I'm a text message');
newNode.appendChild(textNode);
document.body.appendChild(newNode);
Copy the code
The style is set
Manipulating CSS styles in different ways through JavaScript can be done through the style property of the node object.
1. Set styles dynamically
Add inline styles directly inside the element you want to style dynamically. This is done with the htmlElement. style attribute. This property contains inline style information for each element in the document. You can modify the element style directly by setting the properties of this object
Example:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Operating style</title>
</head>
<body>
<p id = 'box'>MJJ</p>
<script type="text/javascript">
var para = document.getElementById('box');
para.style.color = 'white';
para.style.backgroundColor = 'black';
para.style.padding = '10px';
para.style.width = '250px';
para.style.textAlign = 'center';
</script>
</body>
</html>
Copy the code
Effect display:
JavaSript attribute versions of CSS styles are written in small camel case nomenclature, while CSS versions come with concattation (backgroundColor vs. background-color)
2. Classes that manipulate properties to control styles
-
Start by adding the following code to the HTML
<style type="text/css"> .highlight { color: white; background-color: black; padding: 10px; width: 250px; text-align: center; } </style> Copy the code
-
Now let’s switch to the usual method of using HTML manipulations — element.setAttribute () — where there are two parameters, the attribute you want to set on the Element, and the value you want to set for it. In this case, we set the class name highlight in the paragraph:
var para = document.getElementById('box'); para.setAttribute('class'.'highlight'); Copy the code
There are pros and cons to both approaches, and it’s up to you which one you choose. The first is install-free and suitable for simple applications, while the second is more orthodox (no CSS/JavaScript mix, no inline styles, which are considered a bad experience). As you start building bigger and more compelling apps, you’ll probably use the second approach more, but it’s entirely up to you.
The event
An event is an action or something that happens in the system when you program it to tell you that you can respond to it in a certain way if you want. For example, if you click a button on a Web page, you might want to respond to the action by displaying an information box.
A series of events
As mentioned above, an event is an action or something that happens in the system when you program it – the system fires a signal when an event occurs and provides an automatic load of an action (as in: Run some code) mechanism, such as at an airport, when the runway of an aircraft about to take off has been cleared, pilots will receive a signal, as a result of which they begin to take off.
In the Web, an event is triggered in a browser window and is usually bound to a specific part of the interior of the window-perhaps an element, a series of elements, HTML code loaded into the window, or the entire browser window. To name a few different things that could happen:
- The user clicks the mouse or hovers over an element.
- The user presses a key on the keyboard.
- The user resizes the browser or closes the browser window.
- A web page stopped loading.
- Submit the form.
- Play, pause, and close the video.
- An error occurred
The main events are:
The event | instructions |
---|---|
onclick | Mouse click event |
onmouseover | Mouse over event |
onmouseout | Mouse away event |
onchange | Text box content change event |
onselect | Text box content selected event |
onfocus | Cursor focus event |
onblur | Cursor out of focus event |
onload | Page loading event |
Mouse click event (onclick)
Onclick is a mouse-click event that occurs when you click the mouse on a Web page. The block called by the onclick event is also executed, usually in conjunction with the button.
For example, when we click a button, the onClick event is triggered and the sum of two numbers is computed.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function add() {
var a, b, sum;
a = 5;
b = 6;
sum = a + b;
alert('The sum of two numbers is :'+ sum);
}
</script>
</head>
<body>
<input type="button" value="Submit" onclick="add();">
</body>
</html>
Copy the code
Mouse over event (onMouseOver)&& Mouse away event (onMouseOut)
Mouse over event. When the mouse moves over an element, the object initiates the onMouseOver event and executes the program called by the onMouseOver event.
When the mouse moves over an element, the object initiates the onMouseout event and executes the program called by the onMouseout event.
<! doctypehtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box{
width: 200px;
height: 200px;
background-color: red;
}
</style>
<script type="text/javascript">
function over(){
console.log('Switch to green');
}
function out() {
console.log('Switch to red');
}
</script>
</head>
<body>
<div class="box" onmouseover="over();" onmouseout="out()"></div>
</body>
</html>
Copy the code
Cursor focus event (onfocus)&& cursor out-of-focus event (onblur)
When the web page. When the element gets focus, the onfocus event is executed and the program is called for execution. Form controls in particular. The onblur event and onfocus are relative events that trigger the onblur event when the cursor moves away from the current focus element, executing the called program at the same time.
<! doctypehtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function message() {
console.log('Please enter your name');
}
function message2() {
console.log('Please enter your username correctly');
}
</script>
</head>
<body>
<form action="">
<p class="name">
<label for="username">User name:</label>
<input type="text" id="username" onfocus="message();" onblur="message2();">
</p>
<p class="pwd">
<label for="pwd">Password:</label>
<input type="password" id="pwd">
</p>
<input type="submit" value="Registered">
</form>
</body>
</html>
Copy the code
Content selection event (onSelect)
The onSelect event is triggered when the text in the textbox or textfield is selected, and the program with the call is executed.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function select2() {
console.log('Content selected');
}
</script>g
</head>
<body>
<textarea name="" id="" cols="30" rows="10" onselect="select2();">Please write your personal introduction in no less than 200 words!</textarea>
</body>
</html>
Copy the code
Text box content change event (onchange)
The onchange event is triggered by changing the contents of the text box while executing the called program.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function changetext() {
console.log('The content has changed');
}
</script>
</head>
<body>
<input type="text" value="mjj" onchange="changetext();">
</body>
</html>
Copy the code
The onchange event is triggered when the text in the user text box is changed.
Load event (onLoad)
The event occurs immediately after the page loads, executing the called program.
Note: When the page loads, the onlaod event is triggered and written inside the body tag.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function message() {
console.log('Loading, please wait...... ');
}
</script>
</head>
<body onload="message();">
</body>
</html>
Copy the code