1. The introduction of the DOM
1.1 What is DOM
Document Object Model (DOM) is a standard programming interface recommended by W3C to deal with extensible markup language (HTML or XML).
The W3C has defined a set of DOM interfaces that allow you to change the content, structure, and style of a web page.
1.2 the DOM tree
-
Document: A page is a document, represented in the DOM as document
-
Element: All tags in a page are elements, represented by an element in the DOM
-
Nodes: Everything in a web page is a node (tag, attribute, text, comment, etc.), and the DOM uses node to indicate that the DOM treats all of these as objects
2. Get elements
DOM is primarily used to manipulate elements in our actual development.
How do we get elements on the page?
2.1 How do I Obtain Page Elements
You can get elements in a page in one of the following ways:
- Obtain by ID
- Obtained by label name
- Through HTML5 new methods to obtain
- Special element fetch
2. Get elements
2.2 Obtaining data By ID
Use the getElementById() method to get an element object with an ID.
document.getElementById('id');
Using console.dir(), we can print the element object we fetch to better view the properties and methods in the object.
<body>
<div id="time">The 2021-5-26</div>
<script>
// 1. Since the document page is loaded from top to bottom, there must be tags first, so we put the script tag at the bottom
// 2. Get the element by camel naming
// 3. The id parameter is a case-sensitive string
// 4. Returns an element object
var timer = document.getElementById('time');
console.log(timer); //<div id="time">2021-5-26</div>
console.log(typeof timer); //object
// 5.console.dir Prints the element object we return for a better view of its properties and methods
console.dir(timer); // div#time
</script>
</body>
Copy the code
2.3 The value can be obtained by label name
The getElementsByTagName() method returns a collection of objects with the specified label name.
Document. GetElementsByTagName (' tag name ');
Note:
-
Because we get a collection of objects, we need to iterate over the elements that we want to manipulate.
-
Getting the element object is dynamic
-
If no element is retrieved, an empty pseudo-array is returned (because no object was retrieved)
<body>
<ul>
<li>Yes or no, yes or no, it should be 1234</li>
<li>Yes or no, yes or no, it should be 1234</li>
<li>Yes or no, yes or no, it should be 1234</li>
<li>Yes or no, yes or no, it should be 1234</li>
<li>Yes or no, yes or no, it should be 1234</li>
</ul>
<ul id="nav">
<li>skr~</li>
<li>skr~</li>
<li>skr~</li>
<li>skr~</li>
<li>skr~</li>
</ul>
<script>
// 1. Returns a collection of retrieved elements stored as a pseudo-array
var lis = document.getElementById('li');
console.log(lis);
console.log(lis[0]);
// 2. We want to print the element object once
for(var i = 0; i < lis.length; i++){
console.log(lis[i]);
}
/ / 3. Element. GetElementsByTagName () can get the element inside a tag
var nav = document.getElementById('nav'); // Get the nav element
var navLis = nav.getElementsByTagName('li');
console.log('navLis');
</script>
</body>
Copy the code
2.4 Obtain through the new method of HTML5
- Document. The getElementsByClassName (” the name of the class “); // Returns a collection of element objects based on the class name
- Document. querySelector(‘ selector ‘); // Returns the first element object according to the specified selector
- Document. QuerySelectorAll (‘ selector ‘); // Returns based on the specified selector
Note:
The selectors in querySelector and querySelectorAll need symbols, such as document.querySelector(‘#nav’);
2.5 Getting Special Elements (Body, HTML)
Get the body element
- Doucumnet. body // Returns the body element object
Getting HTML elements
- Document.documentelement // Returns an HTML element object
<script>
// 1. Get the body element
var bodyEle = document.body;
console.log(bodyEle);
console.dir(bodyEle);
// 2. Get the HTML element
// var htmlEle = document.html;
var htmlEle = document.documentElement;
console.log(htmlEle);
</script>
Copy the code
3. Event basis
3.1 Event Overview
JavaScript gives us the ability to create dynamic pages, and events are behaviors that can be detected by JavaScript. Simple understanding: trigger – response mechanism. Every element in a web page can generate some event that triggers JavaScript, for example, we can generate an event when a user clicks a button and then perform some action.
3.2 Three elements of the event
- Event Source (who)
- Event type (what event)
- Event handlers (what they do)
There is a button in the page. When the mouse clicks on the button, a “Hello” alert box pops up.
Case analysis
① Obtain the event source (button)
② Register event (bind event), use onclick
③ Write the event handler, write a function to pop up the alert box
The implementation code
var btn = document.getElementById('btn'); Btn.onclick = function() {alert(' hello '); };
<body>
<button id="btn">Tong pak fu</button>
<script>
// Click a button to pop up the dialog box
// 1. An event is composed of three components: event source event type Event handler we also call event triad
//(1) The event source event is triggered by the object which buttons
var btn = document.getElementById('btn');
//(2) How does the event type trigger what events such as mouse click (onclick) or mouse pass or keyboard press
//(3) The event handler is done through a function assignment
btn.onclick = function() {
alert('Light autumn Heung');
}
</script>
</body>
Copy the code
3.3 Steps for executing events
- Obtaining event Sources
- Register events (bind events)
- Add event handlers (in the form of function assignments)
<body>
<div>123</div>
<script>
// Perform the event step
// Click div console to print I am selected
// 1. Obtain event sources
var div = document.querySelector('div');
// 2. Bind events register events
// div.onclick
// 3. Add event handlers
div.onclick = function() {
console.log('I've been chosen');
}
</script>
</body>
Copy the code
3.3 Common Mouse Events
3.4 Analyzing the three elements of the event
The drop-down menu has three elements
Close the three elements of advertising
4. Manipulate elements
JavaScript DOM manipulation can change the content, structure and style of a web page. We can use DOM manipulation elements to change the content, attributes, etc. Note that these are attributes
<body>
<button>Displays the current system time</button>
<div>A certain time</div>
<p>1123</p>
<script>
// When we click the button, the text inside the div will change
// 1. Get the element
var btn = document.querySelector('button');
var div = document.querySelector('div');
// 2. Register events
btn.onclick = function() {
// div.innerText = '2019-6-6';
div.innerHTML = getDate();
}
function getDate() {
var date = new Date(a);// Let's write a date for Wednesday, May 1st, 2019
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = ['Sunday'.'Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'.'Saturday'];
var day = date.getDay();
return 'Today is:' + year + 'years' + month + 'month' + dates + 'day' + arr[day];
}
// We don't need to add events to our element
var p = document.querySelector('p');
p.innerHTML = getDate();
</script>
</body>
Copy the code
4.1 Changing element content
Element. innerText The content of the element from the start to the end, but it strips out the HTML tag. Whitespace and a line feed also strip out the entire content of the Element
<body>
<div></div>
<p>I am writing<span>123</span>
</p>
<script>
// The difference between innerText and innerHTML
// 1. InnerText does not recognize HTML tags. Non-standard whitespace and line breaks are removed
var div = document.querySelector('div');
// div. InnerText = ' today is: 2019';
// innerHTML identifies HTML tags with the W3C standard reserved Spaces and newlines
div.innerHTML = '< /strong> 2019';
// These two attributes are readable and writable and can fetch the contents of the element
var p = document.querySelector('p');
console.log(p.innerText);
console.log(p.innerHTML);
</script>
</body>
Copy the code
4.2 Attribute operations of common elements
- The innerText, innerHTML changes the content of the element
- The SRC, href
- Id, Alt, and title
Case: time display different pictures, display different greetings according to different time, page display different pictures, display different greetings at the same time. If the morning time opens the page, “Good morning” is displayed, and the picture of the morning is displayed. If the afternoon time opens the page, show good afternoon, show the afternoon picture. If evening time opens the page, show good evening, show pictures of the evening.
Case analysis
① According to the different time of the system to judge, so need to use the date built-in object
② Use multi-branch statements to set different pictures
③ You need an image, and you need to modify the image according to the time, you need to use the action element SRC attribute
(4) Need a div element, display different greetings, modify the element content
<style>
img {
width: 300px;
}
</style>
</head>
<body>
<img src="images/s.gif" alt="">
<div>Good morning</div>
<script>
// It depends on the time of the system, so you need to use built-in date objects
// Use multi-branch statements to set different images
// We need an image, and we need to modify the image according to the time, using the SRC attribute of the action element
// You need a div element to display a different greeting. You can modify the contents of the element
// 1. Get the element
var img = document.querySelector('img');
var div = document.querySelector('div');
// 2. Get the current hour
var date = new Date(a);var h = date.getHours();
// 3. Determine the number of hours to change the picture and text message
if (h < 12) {
img.src = 'images/s.gif';
div.innerHTML = 'Good morning, dear. Write code.';
} else if (h < 18) {
img.src = 'images/x.gif';
div.innerHTML = 'Good afternoon, dear. Good code.';
} else {
img.src = 'images/w.gif';
div.innerHTML = 'Good evening, dear. Write code.';
}
</script>
</body>
Copy the code
4.3 Attribute operations of form elements
Using the DOM, you can manipulate the following form element attributes: Type, Value, Checked, Selected, and Disabled
Click the button to switch the password box to a text box, and you can view the password in plain text.
Case analysis
① Core idea: click the eye button, change the password box type to text box, you can see the password inside
② A button with two states, click once to switch to the text box, continue to click once to switch to the password box
③ Algorithm: use a flag variable to determine the value of flag. If it is 1, switch to the text box and flag is set to 0. If it is 0, switch to the password box and flag is set to 1
<style>
.box {
position: relative;
width: 400px;
border-bottom: 1px solid #ccc;
margin: 100px auto;
}
.box input {
width: 370px;
height: 30px;
border: 0;
outline: none;
}
.box img {
position: absolute; top: 2px; right: 2px; width: 24px; } </style> </head> <body> <div class="box"> <label for=""> <img src="images/close.png" alt="" id="eye"> </label> <input type="password" name="" id="pwd"> </div> <script> // 1. Var eye = document.getelementById ('eye'); var pwd = document.getElementById('pwd'); Var flag = 0; Eye.onclick = function() {if (flag == 0) {pwd.type = 'text'; eye.src = 'images/open.png'; flag = 1; } else {pwd.type = 'password'; eye.src = 'images/close.png'; flag = 0; } } </script> </body>Copy the code
4.4 Style Property Operations
We can change the size, color, position and other styles of elements with JS.
- Element. style Inline style manipulation
- Element. className className style operation
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div></div>
<script>
// 1. Get the element
var div = document.querySelector('div');
// 2. Register event handlers
div.onclick = function() {
// Div. Style attributes are humped
this.style.backgroundColor = 'purple';
this.style.width = '250px';
}
</script>
</body>
Copy the code
Note:
1. Styles in JS adopt camel naming methods such as fontSize and backgroundColor
2.JS modify the style operation, resulting in inline style, CSS weight is relatively high