DOM

1. DOMAn overview of the

In previous articles, we learned that the core part of the javascript language, known as ECMAScript, is typically run in a control bar, output statement, or Node environment. Let’s move on to the DOM section.

DOM(Document Object Model) : Document Object Model, which describes a hierarchical number of nodes, allowing developers to add, remove, and modify parts of a page.

This allows JavaScript to manipulate HTML, not strings, but nodes, making it much easier to program

DOM abstracts and provides rich apis for many things: fetching elements, CSS styles, events, movements, element size and location, node operations

Experience DOM manipulation

// Get the element
var box = document.getElementById('box');
var img = document.getElementById('img');
// Modify the CSS style
box.style.backgroundColor = 'lightgreen';
// Mouse over
img.onmouseover = function () {
  img.src = './js1.jpg'
}
// Mouse over
img.onmouseout = function () {
  img.src = './js.jpg'
}
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>DOM</title>
  <style>
    * { padding: 0; margin: 0; }
    div { width: 150px; height: 150px; background-color: lightblue; }
  </style>
</head>
<body>
  <div class="box" id="box">Internal text</div>
  <img src="./js.jpg" alt="js" id="img">
  <script>
    // Get the element
    var box = document.getElementById('box');
    var img = document.getElementById('img');
    // Modify the CSS style
    box.style.backgroundColor = 'lightgreen';
    // Mouse over
    img.onmouseover = function () {
      img.src = './js1.jpg';
    }
    // Mouse over
    img.onmouseout = function () {
      img.src = './js.jpg';
    }
  </script>
</body>
</html>
Copy the code

2. HTMLoperation

JavaScript represents the document through the Document object, which represents the entire page. There are many properties and methods that cover most page features and actions

DOM manipulation: Usually refers to the use of some method to obtain HTML elements on a page and then perform some operations on those elements

Common methods for getting elements

  • document.getElementById(); : Gets the element by id

    Note: you don’t need # in parentheses, just id

    // Error
    var img = document.getElementById('#img');
    Copy the code
  • document.getElementsByTabName(); : Method of getting elements by tag name

The elements obtained by id are object types, and properties and methods can be invoked directly through point operations

console.log(typeof box);
//object
console.log(img.id);
// img
console.log(img.src);
// file:///C:/Users/vience/Desktop/js.jpg
Copy the code

You can assign by using equal =. All other attributes can be assigned, but id cannot, because id is read-only and cannot be changed

document.title = 'HTML operations';
img.src = './js1.jpg';
console.log(img.id); // img
Copy the code

Custom attributes cannot be invoked using dot calls,

console.log(box.hua); //undefined
Copy the code

Custom reading and assignment of properties

Read: getAttribute(Key) Assign: setAttribute(key, value) Key is the name of the user-defined attribute and value is the value of the user-defined attribute

console.log(box.getAttribute('hua'))
/ / rape
box.setAttribute('hua'."Rose")
console.log(box.getAttribute('hua'))
/ / rose
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>HTML operation</title>
  <style>
    * { padding: 0; margin: 0; }
    div { width: 150px; height: 150px; background-color: lightblue; }
  </style>
</head>
<body>
  <div class="box" id="box" hua="Rape flower" style="background-color: antiquewhite; color: #000;">Internal text</div>
  <img src="./js.jpg" alt="js" id="img">
  <input type="button" value="Here's the button." id="btn">
  <script>
    // Get the element by id
    var box = document.getElementById('box');
    var img = document.getElementById('img');
    var btn = document.getElementById('btn');
    console.log(typeof box);
    console.log(img.id);
    console.log(img.src);
    document.title = 'HTML operations';
    img.src = './js1.jpg';
    console.log(box.getAttribute('hua'))
    box.setAttribute('hua'."Rose")
    console.log(box.getAttribute('hua'))
  </script>
</body>
</html>
Copy the code

The difference between point operations and getAttribute(key) and setAttribute(key, value)

  • Point operations can only be used to operate original HTML attributes, but not custom attributes. GetAttribute (key) and setAttribute(key, value) can operate custom attributes or create original attributes

    Console. log(box.getAttribute('hua')) // rapeseed box.setattribute (' Hua ', "rose ") console.log(box.getattribute ('hua')) // RoseCopy the code
  • Point operation When you operate an HTML attribute, the attribute name may need to be changed, but getAttribute(key) and setAttribute(key, value) do not

    • Class = = = "className

    • For = = = "htmlFor

    • Colspan = = = "colspan

    • Rowspan = = = "rowspan

      console.log(box.className);
      // box
      console.log(box.getAttribute('class'));
      // box
      Copy the code
  • A point operation on an object yields an object, while a getAttribute(key) yields a string

    console.log(typeof box.style);
    //object
    console.log( typeof box.getAttribute('style'));
    // string
    Copy the code
  • Dot operation: The style object can continue to dot, but the string obtained by getAttribute(key) cannot continue to dot. The dot operation requires compound attributes and camel name, but the getAttribute(key) does not

    console.log(box.style.backgroundColor);
    // antiquewhite
    Copy the code

Summary: In work, point operations are generally used, and only getAttribute(key) and setAttribute(key, value) are used for custom attributes.

3. CSSoperation

The style we get from the dot operation is an object, and we continue to use the dot operation to call the property

You can only get and set inline styles with style, not computed styles

When you assign an equal sign by getting a property, the value to the right of the equal sign is enclosed in quotes, the CSS style value that needs to be written in quotes

If the style attribute below style is a compound attribute, use camel name.

box.style.backgroundColor = 'pink';
box.style.borderWidth = '10px';

Copy the code

4. Event

Event listening: When our computer parses JavaScript code, it checks to see if events are added to elements. Listen for these events at any time if they are triggered, and perform the corresponding behavior if they are triggered

Common Events

  • onclick: Mouse click event
  • ondbclick: Double-click the mouse
  • onmouseover: Mouse over the event
  • onmouseout: Mouse out event
  • onmousedown: Mouse press event
  • onmouseup: Mouse bouncing event
  • onfocus: Get the focus event
  • onblur: Out-of-focus events
  • onload: Loading completion event

Add event listener method: By adding events to an object, assign a function that executes immediately when the event is raised

box.onclick = fun;
function fun() {
  console.log(box.innerHTML);
}
// Internal text
Copy the code

Method of executing a function: bind a function to an event that executes the bound function immediately

JavaScript familiar position:

Write JavaScript at the end of all HTML elements if you’re writing in the body section

If you write at the bottom of the head, use the window.onload event and wait until the HTML is loaded

window,onload = function () {
    // The statement will be executed after the HTML is loaded
}
Copy the code
// The code written in the head tag
console.log(1)
window.onload = () = > {
    console.log(2)}console.log(3)
// The output sequence is 1, 3, and 2
Copy the code

5. The timer

  1. setInterval

    setInterval(() = > {
      // statement 1
    }, interval);
    Copy the code

    Execute the statement in the arrow function every interval

    The interval is in milliseconds, and the unit is not needed

    var a = 0; setInterval(() => { a ++; console.log(a) }, 1000); // The console prints a number every second, 1, 2, 3, 4...Copy the code
  2. setTimeout

    setTimeout(() = > {
      // statement 2
    }, interval);
    Copy the code

    Execute the statement in the arrow function once after interval

    This command is executed only once. Interval is in milliseconds

    var a = 0;
    setTimeout(() = > {
      a ++;
      console.log(a)
    }, 1000);
    // The console prints 1 after 1 second
    Copy the code