DOM, full name Document Object Model, Chinese translation for the Document Object Model, DOM belongs to the Web API part of the Web API defines a very large number of objects, through which you can complete a variety of operations on the Web page (adding and removing elements, sending requests, operating the browser, etc.)
D in DOM means Document, i.e. document. The so-called document refers to the entire web page, in other words, the DOM is used to manipulate the web page. o means Object, i.e., object, the DOM will be converted into an object for each part of the content of the web page, div has the object of the div, input has the object of the input, and even a paragraph of text, a paragraph of the comment also has its corresponding object. After the conversion of the object, we can operate the web page in an object-oriented way, which element you want to operate on which element to get the object, and then by calling its methods or properties to complete a variety of operations. The model is used to represent the relationship between objects, that is, parent-child elements, ancestor-descendant, brother elements, etc. After clarifying the relationship, we can obtain other objects through any one of them.
Various elements in a web page (e.g., labels, text, attributes, etc.) are represented as objects, which are organized in a tree-like structure called the DOM tree
For example, for a simple HTML page
Hello, World!
The root node of its DOM tree is html, under the html node there is a body child node, under the body node there is a p child node, and the p node contains the text content "Hello, World!"
document object
To use the DOM to manipulate a web page, my browser has to give me at least one object before I can go through the various operations, the browser has provided us with a document object, which is a global variable that can be used directly to
<body>
<button id = "btn"> button </button>
<script>
// Get the btn object by its id
const btn = ("btn")
// Change the button text to a new button
// innerText is used to get or set the text inside the element.
= "New Button"
</script>
</body>
- The document object represents the entire web page
- The prototype chain of the document object
HTMLDocument -> Document -> Node -> EventTarget -> -> null
- The properties and methods of any object that exists in the prototype chain can be called through Document.
- Partial Properties:
--> html root element
--> head element
--> title element
--> body element
--> Get all hyperlinks on the page - The Complete List of Usage
- The prototype chain of the document object
nodal
Under the DOM standard, every part of a web page is converted into an object. These objects have a common name - nodes (Node). A page will consist of multiple nodes, and although they are all called nodes, they are of different types: document nodes, element nodes, text nodes, attribute nodes ....
Each node has its own role, the document node represents the entire web page, the element node represents a label, the text node represents the text content of the web page, and the attribute node represents the various attributes of the label. If from the structure of the object, these objects have a common parent class Node. in general, all belong to the node, but the specific type of different
element node
element node object (element), in the web page, each label is an element node
<body>
<button id = "btn" class="btn-class"> button</button>
<input type="radio" name="one">
<script>
// Get the element node object by id
const btnId = ("btn")
(btnId) // <button class="btn-class"> button</button>
// Get all eligible elements condition objects by class, returning an array of class objects
// The result of this method is a collection that is updated in real time as new elements are added to the page.
const btnClass = ("btn-class")
(btnClass) // HTMLCollection[button#-class, btn: button#-class]
// Get a set of element node objects based on tag names
// This method returns a collection that is updated in real time as new elements are added to the page.
// ("*") Get all the elements in the page.
const btnTag = ("button")
(btnTag) // HTMLCollection[button#-class, btn: button#-class]
// Get a set of element node objects based on the name attribute, returning a collection that is updated on the fly, mainly for forms.
const inputName = ("one")
(inputName) // NodeList[input]
// Query the page for elements based on various css selectors, returns an array of classes (not updated in real time)
const query = (".btn-class")
(query) // NodeList[button#-class]
// Go to the first element on the page that matches the criteria based on the selector, if it doesn't return null
const firstQuery = ("button")
(firstQuery) // <button class="btn-class"> button</button>
// Create an element node object based on the tag name, just create it, not insert it into the page.
const newTag = ("h1")
(newTag) // <h1> </h1>
</script>
/body> </h1> </script>
/*
Getting other nodes via element node objects
*/
<body>
<div id = "box">
<button id = "btn" class="btn-class"> button</button>
<input type="radio" name="one">
</div>
<button class="btn-class"> button 2</button>
<script>
const element = ("box")
// The methods of the document object can be used in the same way for the element node object, but the difference is that they get the specified object within the current object.
// Get the button object within element
const btn = ("button")
(btn) // HTMLCollection[button#-class, btn: button#-class]
// Get the child nodes of the current element (including blank ones)
const childNodes =
(childNodes) // NodeList(5) [text, button#-class, text, input, text]
// Get the children of the current element
const children =
(children) // HTMLCollection(2) [button#-class, input, btn: button#-class, one: input]
// Get the first child of the current element
const firstElementChild =
(firstElementChild) // <button id = "btn" class="btn-class"> button</button>
// Get the last child of the current element
const lastElementChild =
(lastElementChild) // <input type="radio" name="one">
// Get the next sibling of the current element
const nextElementSibling =
(nextElementSibling) // <button class="btn-class"> button2</button>;
// Get the previous sibling of the current element
const previousElementSibling =
(previousElementSibling) // null
// Get the parent node of the current element
const parentNode =
(parentNode) // <body>... </body>
// Get the tag name of the current element
const tagName =
(tagName) // DIV
</script>
</body>
text node
In the DOM, all text content in a web page is a text node object, including empty text, line breaks and spaces.
<body>
<div id = "box">
asdasd
<button id = "btn" class="btn-class"> button</button>
<input type="radio" name="one">
</div>
<button class="btn-class"> button 2</button>
<script>
// It's possible to get the text node object from the element, but we don't usually do that, so we can modify the text directly from the element.
const element = ("box")
const t =
(t) // asdasd
</script>
</body>.
Modify the text directly through the element
<body>
<div id = "box">
asdasd
<button id = "btn" class="btn-class"> button</button>
<input type="radio" name="one">
</div>
<button class="btn-class"> button 2</button>
<script>
const element = ("box")
// textContent gets or modifies the text content of the element, it gets the content of the tags, it doesn't take into account the css styles.
// When there are tags in the string, the tags are automatically escaped and displayed on the page, not rendered.
// If you change something, it takes effect on the page.
() // Get the text:asdasd button.
() // Get the text of the first child of element:asdasd
= "new t" // change the first text to new t
// innerText gets or modifies the text content in the element, taking into account css styles, which triggers a rearrangement of the page (calculating CSS styles)
// When there are tags in the string, the tags are automatically escaped and displayed on the page, not rendered.
// If a change is made, it takes effect directly on the page
// Get the text of the element's first child node.
() // Button
= "Big Button" // Modify the text of the element's first element child.
// innerHTML gets or modifies the html code in the element, you can add html code directly to the element, innerHTML inserts content, there is a risk of xss injection.
// When there is a tag in the string, it will take effect on the web page.
() // The 'big button'
= "<h1> new big button </h1>" // h1 effect will take effect on the web page
</script>
</body>
property node
Attribute node (Attr) in the DOM is also an object, usually do not need to get the object but directly through the element can be completed on its various operations
<input class="admin" type="text" name="username" value="user">
<input class="admin1" type="text" name="username1" value="user1">
<script>
const input = ("[name=username]")
const input2 = (".admin1")
// You can read and modify the corresponding data by using the element. Attribute names can be read and modified.
() // admin, reading the class attribute is special, you need to use className.
() // text
() // username
= "new user" // Change the value to new user.
() // false Returns true or false when reading a boolean value.
// Reading and modifying an object's properties via methods
// Reading properties
(("type")) // text
// Modify the attribute by changing the value of the value attribute to uuu
("value", "uuu")
// Delete the attribute
("value")
</script>
</body>
event
Event
- Events are interactions that occur between the user and the page
For example: clicking on a button, moving the mouse, double-clicking on a button, hitting the keyboard, releasing a key...- Interaction with the user can be accomplished by binding a response function (callback function) to the event.
- The way to bind the response function:
1. Can be set directly in the attributes of the element
2. Events can be bound in the form of callback functions for specified attributes of an element (an event can only be bound to one response function)
3. You can bind events through the element addEventListener() method.
<body>
<button >click</button>;
<script>
// Get the button object
const btn = ("btn")
// Set a response function for the button's click event, this way only one response function can be bound to an event, and it will be overwritten if it's bound again and again
= function (){
alert("onclick!!!")
}
// Bind the event via addEventListener. The first parameter is the event that triggered it, and the second parameter is the response function.
// This way an event can be bound to multiple response functions, which are executed in the order in which they are bound.
("click",function (){ ("addEventListener",function (){
("addEventListener")
})
("click",function (){
alert("addEventListener")
})
</script>
</body>
Loading of documents
Web pages are loaded from the top down, if the js code is written to the top of the web page, js code in the execution of the web page has not been loaded, then there will be unable to get to the DOM object of the situation
How to solve this problem:
1. write the script tag at the end of the body 2. write the code into the callback function of the document object. 3. write the code into the DOMContentLoaded callback function of the document object (earlier execution time) 4. write the code to an external js file and introduce it as a defer (earlier, before DOMContentLoaded)
<script>
// The event is triggered after all the content in the window (a web page may have embedded pages) has been loaded.
// The response function is triggered to execute the js code after the window content is loaded.
= function () {
// Get the button object
const btn = ("btn")
("click", function () {
alert("addEventListener")
})
}
</script>
<body>
<button > click </button> <body>
</body>
// The DOMContentLoaded event is executed after the current document is loaded.
("DOMContentLoaded",function (){
// Get the button object
const btn = ("btn")
("click", function () {
alert("addEventListener")
})
})
<! -- Introducing external js files -- >!
<! -- If introduced on body by default, there will still be load timing issues -->!
<! -- The defer keyword delays loading until the current document is loaded, solving the problem --> <!
< script defer src = ". /script/"> </script>
Modification of DOM elements
Creating Elements
appendChild
appendChild() is a method of the DOM node object. Its main purpose is to add a node to the end of the list of children of another node. This is a way to dynamically add elements to the structure of an HTML document
<body>
<button >button</button>;
<ul >
<li >1</li>
<li >2</li>
<li >3</li> <li >3</li>
/ul> </ul>.
</body>.
<script>
// Get the ul
const list = ("list")
// Get the buttons
const btn = ("btn")
// Triggered when the button is clicked
= function (){
// Create a li
const li = ("li")
// The text of the li
= "4"
// Set the id of the li
= "four"
// Add the created li element to ul
// appendChild adds a node to another node
(li)
}
</script>
insertAdjacentElement
insertAdjacentElement() is a DOM action method in js. It is used to insert a specified element into the vicinity of another element at a specific location.
// Triggered when the button is clicked
= function (){
// Create a li
const li = ("li")
// The text of the li
= "4"
// Set the id of the li
= "four"
// Add the created li element to the ul
// Parameters:1. position to add 2. element to add
("afterbegin",li)
// the end of the beforeend tag the beginning of the afterbegin tag
// beforebegin inserts the element before the element (sibling) afterend inserts the element after the element (sibling)
}
insertAdjacentHTML
insertAdjacentHTML() method for inserting an HTML string in the vicinity of a specified element. Allows you to insert HTML code snippets as strings in different locations of the element, risking XSS attacks
// Triggered when the button is clicked
= function (){
// Parameters: 1. position to add 2. html code string to insert
("afterbegin","<li id='5'>5</li>>")
// the end of the beforeend tag the beginning of the afterbegin tag
// beforebegin inserts the element before the element (sibling element) afterend inserts the element after the element (sibling element)
}
Replacement element
// Get the li with id=one
const one = ("one")
// Create a new li
const newOne = ("li")
= "1111"
= "new-one"
// replaceWith replaces the current element with one element
// newOne replaces one
(newOne)
Delete element
const two = ("two")
// The remove() method is used to remove the current element.
()
Remove the default behavior of an element
<! --javascript:; Execute the code But the code is empty, i.e. no behavioral action occurs -->
<a href="javascript:;"> </a>
Using return false to cancel the default behavior only applies to events bound in the form = function(){}
// Response function
function delUserInfo(){
// Binds this response function to all hyperlinks, this is whichever link is clicked.
// parentNode is a node property. It is used to get the parent node of the current node
const tr =
// Get the user's nickname
const userName =
// confirm() is a browser-provided global function that displays a modal dialog box with "OK" and "Cancel" buttons. This dialog asks the user a yes/no question and waits for the user's response
if (confirm(`Confirm you want to delete ${userName}`)){
()
}
// Cancel the default event
return false
}
// Get all hyperlinks
const links =
// Bind a single-level response function to all links
for (let link of links){
= delUserInfo
}
Replication of nodes
// Get the list of ul's
const list = ("list")
// Get the element node with id li1
const li1 = ("li1")
// Make a copy of the li1 node and assign it to newLi
const newLi = (true)
= "li2"
(newLi)
/*
When a node is cloned using the cloneNode() method, it copies all of the node's characteristics, including its various attributes.
By default, this method will only clone the current node, not its children.
A true argument can be passed so that the method also copies the children of the element.
*/
Manipulating css through the DOM
Reading and modifying inline styles with style
// Get the box element
const box = ("box")
// Modify the inline style of box
= "400px"
= "400px"
// If the style name contains a -, change the stylesheet to camel nomenclature,background-color --> backgroundColor
= "yellow"
// Read inline styles
()
Retrieve the style currently in effect
// Get the box element
const box = ("box")
// getComputedStyle returns a read-only object containing all the styles in effect for the current element, which cannot be modified in this way.
// Parameters: the object to get the style from, and the pseudo-element to get it from.
const styleObj = (box)
// The width of the currently active element.
()
// The height of the currently active style.
()
// Get the style of the before pseudo-element
const styleObj1 = (box,"::before")
()
Other ways to read styles
// Get the box element
const box = ("box")
// Get the width and height of the inside of the element, including the content area and inner margins.
()
()
// Get the size of the element's visible frame, including the content area, inner margins, and borders.
()
()
// Get the width and height of the element's scroll area.
()
()
// Get the element's positioned parent, the nearest ancestor with positioning enabled, or body if all elements do not have positioning enabled.
()
// Get the offset of the element relative to its positioned parent.
()
()
// Get or set the offset of the element's scrollbar
()
()
= 100 // Set the offset
Manipulating class to modify css styles
In addition to modifying the style directly, you can also modify the style indirectly by modifying the class attribute.
<style>
.btn{
width: 200px;
}
</style>.
<script>
const btn1 = ("btn1")
const btn2 = ("btn2")
// Add a btn class to the original class name.
// Set the style with a class selector hit in css style
+= " btn"
+= " btn"
</script>
Benefits of modifying styles via class:
1. Can modify multiple styles at once
2. decoupling of JS and CSS
const btn1 = ("btn1")
// The element.classList is an object that provides various methods for manipulating the class of the current element.
// Add one or more classes to the element.
("btn2", "btn3")
// Remove one or more classes from the element.
("btn2")
// Toggle the classes in the element, removing the class of btn2 if it exists, adding it if it doesn't
("btn2")
// Replace the class, replacing btn1 with btn2.
("btn1", "btn2")
// Check the class, return true if the class is present, false otherwise.
("btn1")
event object
Event Object:
An event object is an object created by the browser when an event is triggered, which encapsulates various information related to the event.
Through the event object can get to the event details, such as: mouse coordinates, keyboard keys....
After the browser creates the event object, it passes the event object as an argument to the response function, the
So we can define a formal parameter in the event's callback function to receive the event object
const box = ("box")
// Listening to events, after the event object is created, the event object is passed as a parameter to the response function, and a formal parameter is defined in the event's callback function to receive the event object
("mousemove",event => {
(event) // An object containing many properties and methods, depending on the type of event triggered.
() // Get the x-axis
() // Get the y-axis.
})
("click",function (event){
(event)
})
Event object
In the DOM there are many different types of event objects, many event objects have a common ancestor Event
const box = ("box")
("click", event => {
// The object that triggered the event
() // The element with id box
// The object to bind the event to (related to event bubbling), same as this
()
/*
- Event bubbling is the upward propagation of events.
- When an event is triggered on an element, the same event is triggered on its ancestor, from the inside out.
- The existence of bubbling greatly simplifies coding, but in some scenarios we don't want bubbling, and can cancel it with an event object.
- Event bubbling has nothing to do with the style of the element and everything to do with the structure.
// Cancel event conduction (the event object is not a style element, it's a structure element).
// Cancel event conduction (bubbling).
()
// Cancel the default behavior
()
})
Incident assignment
Binding events only once allows all element objects, including current and future new ones, to have those events.
Delegation is the event that should be bound to multiple elements, unified binding to the document and then according to the judgment logic triggered by what elements, which can reduce the complexity of the code to facilitate the maintenance of the
<body>
<button >button</button>;
<ul >
<li> <a href="#">1</a> </li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</body>
<script>
const list = ("list")
const btn = ("btn")
// Get all the hyperlinks in the list
const links = ("a")
// You can bind the events to the document uniformly, so that the click event bubbles up and causes the click event on the document to be triggered.
// This way it's only bound once, and all clicks will have these events
("click", (event) => {
// Determine who triggered the event and if it exists in the links.
// Only clicks on hyperlinks in the list take effect, if you don't judge the event, all clicks on the page will take effect
if ([... .links].includes()) {
if ([...links].includes()) { alert()
}
})
// Add a new li to the ul after clicking the button
("click", () => {
("beforeend", "<li><a href='#'>new</a></li>")}
)
</script>.
Event Capture
In the DOM, the propagation of events can be divided into three stages:
1. Capture phase (capture of an event from an ancestor element to a target element) (by default, events are not triggered in the capture phase)
2. Target phase (the object that triggers the event)
3. Bubbling phase (bubbling of events from the target element to the ancestor element)
Capture of events refers to the conduction of events from the outside in: the
- When an event is triggered on the current element, the event will be captured from the largest ancestor of the current element.
- Bubbling is from the inside out, while capturing is from the outside in.
const box = ("box")
("click", event => {
// eventPhase indicates the stage at which the event is triggered.
()
// If you want the event to be triggered during the capture phase, you can set the third parameter of addEventListener to true
}, true)