6. Front End Development-JavaScript DOM

6. Front End Development Language System-JavaScript DOM

Article Directory

JavaScript DOM

Introduction to DOM

The so-called DOM, fully known as the Docuemnt Object Model document object model.

Everything in the document is an object, such as html,body,div,p, and so on.DOM provides a structured representation of a document and defines how to access the document structure through scripting.The purpose is to make js operate on HTML elements.

Parsing process: HTML loading is complete, the rendering engine will in memory put the HTML document, generate a DOM tree, getElementById is to get the element node on the DOM.Then when you do that, you modify the properties of that element.

DOM Method

DOM methods are actions that you can perform (on HTML elements), and DOM attributes are values of HTML elements that you can set or change.

<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
//In this example, getElementById is a method that uses id="demo" to find elements
//innerHTML is an attribute that can be used to obtain or replace the content of HTML elements.
  • Find HTML elements
Method describe
document.getElementById(id) Find elements by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
  • Changing HTML elements
Method describe
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Changing attribute values of HTML elements
element.setAttribute(attribute, value) Changing attribute values of HTML elements
element.style.property = new style Change the style of HTML elements
  • Add and remove elements
Method describe
document.createElement(element) Create HTML elements
document.removeChild(element) Delete HTML elements
document.appendChild(element) Add HTML elements
document.replaceChild(element) Replace HTML elements
document.write(text) Write HTML output stream

DOM Events

JS is an event-driven language with three elements:

  • Event source: html tag that causes subsequent events
  • Event: js is already defined, such as onclick
  • Event Driver: Operations on styles and html.That is DOM

The code writing steps are as follows:

  1. Get the event source: document.getElementById("box");
  2. Binding events: event source box. event onclick and function() {event driver}
  3. Write Event Driver: Operations on DOM

Common events are:

Event Name describe
onclick Mouse Click
ondblclick dblclick
onkeyup Triggered when a key on the keyboard is pressed and released
onchange Text content or options in drop-down menus change
onfocus Get focus, indicate text box, etc. get mouse cursor
onblur Loss of focus, indicating loss of mouse cursor, text box, etc.
onmouseover Mouse hover, i.e. mouse over a picture, etc.
onmouseout Mouse move out, that is, the mouse leaves the area such as the picture
onload Page Document Loading Events
onunload When closing a web page
onsubmit Form Submission Events
onreset When resetting the form

How events are bound:

  1. Direct binding of anonymous functions
//The first way to bind events
var oDiv = document.getElementById("box");
oDiv.onclick = function(){
    alert("I am the pop-up content");      
};
  1. Define the function separately before binding
//The second way to bind events is out-of-line binding and in-line binding

//Out-of-line binding
var oDiv = document.getElementById("box");
    oDiv.onclick = fn;    //Note that this is fn, not fn()
    //Define functions separately
    function fn(){
          alert("I am the pop-up content")      
    }

//In-line binding
<div id="box" onclick="fn()"></div> //Here is fn()

<script type="text/javascript">
    function fn() {
        alert("I am the pop-up content");
    }
</script>

The window.onload() function is called when the page is loaded (when documents and pictures are loaded), the document is loaded first, and the picture resource is loaded later.

JS is loaded synchronously with html.Therefore, if you use an element to redefine an element before it is easy to make mistakes, then the onload event will come in handy, and we can keep the code that uses the element inside the onload to ensure that it is the last one to execute.

<script type="text/javascript">
    window.onload = function () {
        console.log("alex");  //When the page is loaded, print the string
    }
</script>

Problems with the window.onload() method:

  • The onload method is called only after the picture is loaded. If the user visits the JD Shop page now, if the script file in the JD Shop is called in the window.onload() method, if the user's network speed card fails at this time, then the user can't do anything, so the winodw.onload() method has a big problem.
  • window.onload() method If two of these methods are written in a script, there will be event overrides.

DOM Event Listener

There are two methods of event propagation in HTML DOM: bubble and capture.

Event propagation is a method of defining the order of elements when an event occurs.If there is a < p > inside the < div > element and the user clicks on this < p > element, which element "click" event should be handled first?

  • In bubbling, the events of the innermost element are processed first, then the outermost element.The click event for the < p > element is processed first, followed by the click event for the < div > element.
  • In capture, events for the outermost element are processed first, then more inward.The click event for the < div > element is handled first, followed by the click event for the < p > element.

In order to be compatible with more browsers, it is recommended to use more bubble streams.

DOM event monitoring has two methods:

  • addEventListener() method
  • removeEventListener() method

The addEventListener() method specifies event handlers for specified elements. It attaches event handlers to elements without overwriting existing event handlers. We can add multiple event handlers to an element.

The syntax of the addEventListener() method is:

element.addEventListener(event, function, useCapture);

The first parameter is the type of event (such as "click" or "mousedown").
The second parameter is the function we need to call when the event occurs.
The third parameter is a Boolean value, specifying whether to use event bubbling or event capture.This parameter is optional.

Note: Do not use the "on" prefix for events; use "click" instead of "on click".

An example of adding different types of events to the same element:

element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);

function myFunction() {
    alert ("Hello World!");
}
function mySecondFunction() {
    alert ("This is JavaScript!");
}

addEventListener() allows you to add event listeners to any HTML DOM object, such as an HTML element, HTML object, window object, or other object that supports events.

Add an event listener that triggers when the user resizes the window:

window.addEventListener("resize", function(){
    document.getElementById("demo").innerHTML = sometext;
});

The removeEventListener() method deletes event handlers that have been attached through the addEventListener() method.

The syntax of the removeEventListener() method is:

element.removeEventListener(event, function);

The first parameter is the type of event (such as "click" or "mousedown").
The second parameter is the function we need to call when the event occurs.

Example:

element.removeEventListener("mousemove", myFunction);

The addEventListener() and removeEventListener() methods are not supported in IE 8, Opera 6.0, and earlier versions.Cross-browser solutions are:

var x = document.getElementById("myBtn");
if (x.addEventListener) {                    // For mainstream browsers, except IE 8 and corrections
    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {                  // For IE 8 and earlier versions
    x.attachEvent("onclick", myFunction);
} 

DOM Styles and Interactions

HTML DOM allows JavaScript to change the style of HTML elements.

  • Style attributes operate on the attributes in the style tag and control the display:none|block, background:red|green, etc. of the box model through js.
<div id='box'></div>
<script>
    window.onload = function(){
        //1. Get the event source (event objects, all tags in the document are objects)
        var oDiv = docuement.getElementById('box');

        //2. Binding events
        oDiv.onclick = function(){
            //3. Event Driver ps: Remember that all style s used like margin-left are assigned with the marginLeft attribute when they operate on js
            oDiv.style.backgroundColor = 'yellow';
        }
    };

</script>
  • The operation of value is to set and get the text content in the middle of the label.
    • Double closing tag: innerText or innerHTML
    • Single Closed Label: In addition to the img tag, there are input s left, assigning with value
<div id='box'></div>
<input type='text' value = 'alex' id='user'>
<script>
    window.onload = function(){
        //1. Get the event source (event objects, all tags in the document are objects)
        var oDiv = docuement.getElementById('box');
         var oInput = docuement.getElementById('user');
        //2. Binding events
        oDiv.onclick = function(){
            //3. Event Driver  
            oDiv.innerText = 'alex';//Set text content only
            oDiv.innerHTML = '<h1>alex</h1>';//Parse labels with text content
        };

        //2. Binding events
        oInput.onclick = function(){
            //3. Event drivers can only use value assignment and setting values if they have a value attribute
            oInput.value = 'wusir';
        }
    };

</script>
  • Tag attribute operation is the operation on the attributes in the tag.For example, id, class, title, img in each tag.And src and alt attributes in tags, href attributes in a tag, name and type attributes in input tags, and so on.
<script>
        //Requirement: Mouse over img and change to another picture, that is, modify the path (the value of src).
        window.onload = function () {
            //1. Get the event source
            var oImg = document.getElementById("box");
            //2. Binding Events (Hover Events: Mouse enters the event source and immediately starts the event)
            oImg.onmouseover = function () {
                //3. Write Event Driver (Modify src)
                img.src = "image/jd2.png";
//                this.src = "image/jd2.png";
            }

            //2. Binding Events (Hover Events: Mouse enters the event source and immediately starts the event)
            oImg.onmouseout = function () {
                //3. Write Event Driver (Modify src)
                img.src = "image/jd1.png";
            }
        }
    </script>

We use functions to manipulate nodes.

  • Create Node
    • Syntax: new tag (element node) = document.createElement (label name);
<script type="text/javascript">
    var a1 = document.createElement("li");   //Create a li tag
    var a2 = document.createElement("adbc"); //Create a label that does not exist

    console.log(a1);
    console.log(a2);

    console.log(typeof a1);
    console.log(typeof a2);
</script>
  • Insert Node
    • Mode 1: A new child node is inserted at the end of the parent point.
    • Style 1 Syntax: parent node.appendChild (new child node);
    • Mode 2: Insert a new node before the reference node.
    • Style 2 Syntax: Father point. insertBefore (as a reference child node)
  • Delete Node
    • Syntax: parent node.removeChild (child node);

DOM Related Cases

Simple message board:

We type in the text box

  • Click the Message button to add it to the current page.
  • Click the Statistics button to count how many messages are on the current page
  • Clicking the Delete button (red cross) after the message will delete the current message
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Message Board</title>
        <style type="text/css">
            *{
                padding: 0;
                margin: 0;
            }
            body{
            	margin-left: 30%;
            	margin-top: 2%;
            }
            h1{
            	margin-left: 60px;
            }
            #msg{
            	width: 300px;
            	height: 120px;
            }
            #btn{
            	width: 40px;
            	height: 25px;
            }
            .close{
                display: inline-block;
                width: 20px;
                height: 20px;
                line-height: 20px;
                text-align: center;
                cursor: pointer;
                background-color: rgba(0,0,0,.1);
                margin-left: 20px;
                background-color: red;
            }
        </style>
    </head>
    <body>
        <h1>Simple message board</h1>
        <textarea id="msg"></textarea>
        <input type="button" id="btn" value="Leaving a message."/>
        <button id="btn" onclick="sum()">Statistics</button>

        <div id="box">
            <!--<ul>
            </ul>-->

        </div>
    </body>
    <script type="text/javascript">

        // 0 Add ul tag to div#box tag
        var oUl = document.createElement('ul');
        var oBox = document.getElementById('box');
        oBox.appendChild(oUl);

        var oBtn = document.getElementById('btn');
        var oMsg = document.getElementById('msg')
        // Control the total number of messages
        var count = 0;
        oBtn.onclick = function(){

            // Click Message Button Event Action
            // 1. Create a li tag
            var oLi = document.createElement('li');        
            //2. Setting up content
            oLi.innerHTML = oMsg.value + "<span class='close'>X</span>"

            // 3. If you want to continue adding the li tag before the first lifetch inserted
            //3.1 Get the li tag
            var olis = document.getElementsByTagName('li');
             //3.2 If it's the first time you add the li tag, add it directly after ul
            if(olis.length == 0){
                oUl.appendChild(oLi);
                count++;

            }else{
                // 3.3 If it's not the first li tag added, insert it before the first li tag
                oUl.insertBefore(oLi,olis[0]);
                count++;
            }
            // 4. Empty the textarea value after adding
            oMsg.value = '';


            // 5. Delete the current data when you click X
            //5.1 Get all X's first
            var oSpans = document.getElementsByTagName('span');

            // 5.2for loop adds click events to all X
            for(var i = 0; i< oSpans.length; i++){
                oSpans[i].onclick  = function(){
                    // 5.3 Remove the current li tag
                    oUl.removeChild(this.parentNode)
                    count--;
                }
            }

        }

        function sum(){
            alert('Altogether released'+count+'Messages');
        }
    </script>
</html>

Reference Article

JavaScript-DOM (focus)

W3School-JavaScript HTML DOM

Event Models in JavaScript

33 original articles published. Praise 5. Visits 1626
Private letter follow

Tags: Javascript Attribute IE network

Posted on Mon, 10 Feb 2020 23:31:34 -0500 by aktell