Webapis DOM, get elements, event basis, operation elements, recommended collection!

Web APIs

Learning objectives:

Can get elements through ID
Ability to get elements by tag name
Can get elements through class
Ability to get elements through selectors
Can get body and html elements
Ability to register events for elements
Ability to modify element content
Be able to distinguish between innerText and innerHTML
Ability to modify attributes of common elements like div
Ability to modify attributes of form elements
Ability to modify style attributes of elements

1.1. Introduction to web API

1.1.1 concept of API

API (Application Programming Interface) is a pre-defined function, which aims to provide the ability of application program and developers to access a set of routines based on a certain software or hardware, without access to the source code, without understanding the details of its internal working mechanism, just calling and using directly.

Give an example to explain what an API is.

For example,

C language has a function fopen() to open files on the hard disk. For us, this function is a tool provided by C language to open files.

In javascript, there is a function alert() that can pop up a prompt box on the page. This function is a pop-up tool provided by js.

These tools (functions) are provided by the programming language, and the internal implementation has been encapsulated. We just need to learn how to use these tools flexibly.

1.1.2 concept of Web API

Web API is a set of APIs (BOM and DOM) provided by browser to operate browser functions and page elements.

At this stage, we mainly explain the common API for browsers, mainly for the interaction effect of browsers. For example, if we want the browser to pop up a warning box, we can use alert directly

MDN detailed API: https://developer.mozilla.org/zh-cn/docs/web/api

Because there are many Web APIs, we call this stage Web APIs.

The Web API here refers to a series of APIs (many functions or object methods) provided by browsers, that is, a series of tools for operating web pages. For example: how to operate html tags and page addresses.

1.1.3 API and web API summary

  1. API is an interface provided for our programmers, which helps us to realize some functions. We can use it without tangle about how to implement it internally

  2. The Web API is mainly aimed at the interface provided by the browser, and mainly aims at the interaction effect of the browser.

  3. Generally, web APIs have input and output (function parameters and return values). Many web APIs are methods (functions)

  4. Learning Web API can be combined with the idea of learning built-in object method

1.2. DOM introduction

1.2.1 what is DOM

The Document Object Model (DOM) is W3C Treatment recommended by the organization Extensible markup language (html or xhtml) standard Programming interface.

W3C has defined a series of DOM interfaces, through which the content, structure and style of web pages can be changed.

DOM is a set of specifications developed by W3C organization for processing html and xml documents. All browsers follow this set of standards.

1.2.2. DOM tree

DOM tree, also known as document tree model, maps documents into tree structure, and processes them through node objects. The processed results can be added to the current page.

  • Document: a page is a document, which is represented by document in DOM
  • Node: all content in a web page is a node (label, attribute, text, comment, etc.) in the document tree, which is represented by node
  • Tag node: all tags in a web page, usually referred to as element node, or "element" for short, are represented by element

1.3. Get element

Why get page elements?

For example: if we want to operate a part of the page (show / hide, animation), we need to obtain the corresponding elements of the part first, and then operate it.

1.3.1. Get according to ID

Syntax: document.getElementById(id)
Role: get element object according to ID
 Parameter: id value, case sensitive string
 Return value: element object or null

Case code

<body>
    <div id="time">2019-9-9</div>
    <script>
        // Because our document page is loaded from top to bottom, we need to have a tag first, so our script is written below the tag
        var timer = document.getElementById('time');
        console.log(timer);
        console.log(typeof timer);
        // console.dir print the returned element object to better view the properties and methods in it
        console.dir(timer);
    </script>
</body>

1.3.2. Get elements according to tag name

Syntax: document.getElementsByTagName('tagname ') or element.getElementsByTagName('tagname') 
Function: get element object according to label name
 Parameters: label names
 Return value: collection of element objects (pseudo array, array elements are element objects)

Case code

<body>
    <ul>
        <li>I have to wait for you for a long time11</li>
        <li>I have to wait for you for a long time22</li>
        <li>I have to wait for you for a long time33</li>
        <li>I have to wait for you for a long time44</li>
        <li>I have to wait for you for a long time55</li>
    </ul>
    <ul id="nav">
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
        <li>Rare words</li>
    </ul>
    <script>
        // 1. The returned object is a collection of acquired element objects stored in the form of a pseudo array
        var lis = document.getElementsByTagName('li');
        console.log(lis);
        console.log(lis[0]);
        // 2. If we want to print the element objects in turn, we can traverse them
        for (var i = 0; i < lis.length; i++) {
            console.log(lis[i]);
        }
        // 3. element.getElementsByTagName() can get some tags in this element
        var nav = document.getElementById('nav'); // This gets the nav element
        var navLis = nav.getElementsByTagName('li');
        console.log(navLis);
    </script>
</body>

Note: getElementsByTagName() gets a dynamic collection, that is, when the page adds a tag, the collection also adds elements.

1.3.3. H5 new element acquisition method

Case code

<body>
    <div class="box">Box1</div>
    <div class="box">Box2</div>
    <div id="nav">
        <ul>
            <li>home page</li>
            <li>product</li>
        </ul>
    </div>
    <script>
        // 1. getElementsByClassName gets some element sets according to the class name
        var boxs = document.getElementsByClassName('box');
        console.log(boxs);
        // 2. querySelector returns the first element object of the specified selector. Remember that the selector needs to be signed. Box ා NAV
        var firstBox = document.querySelector('.box');
        console.log(firstBox);
        var nav = document.querySelector('#nav');
        console.log(nav);
        var li = document.querySelector('li');
        console.log(li);
        // 3. querySelectorAll() returns the collection of all element objects of the specified selector
        var allBox = document.querySelectorAll('.box');
        console.log(allBox);
        var lis = document.querySelectorAll('li');
        console.log(lis);
    </script>
</body>

1.3.4 get special elements (body, html)

1.4. Event basis

1.4.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 events that trigger JavaScript. For example, we can generate an event when a user clicks a button, and then perform certain operations.

1.4.2. Three elements of the event

  • Event source (who): the element that triggered the event
  • Event type (what event): for example, click event
  • Event handler (what to do): code to be executed after event triggering (function form), event handler

Case code

<body>
    <button id="btn">Tang Pahu</button>
    <script>
        // Click a button to open a dialog box
        // 1. Event is composed of three parts event source event type event handler we also call event three elements
        //(1) Event source event triggered object who button
        var btn = document.getElementById('btn');
        //(2) How do event types trigger events such as onclick, mouse passing or keyboard pressing
        //(3) The event handler is completed by a function assignment
        btn.onclick = function() {
            alert('Autumn fragrance');
        }
    </script>
</body>

1.4.3. Steps to execute the event

Case code

<body>
    <div>123</div>
    <script>
        // Perform event steps
        // Click on the div console to output that I have been selected
        // 1. Get event source
        var div = document.querySelector('div');
        // 2. Bind event registration event
        // div.onclick 
        // 3. Add event handler 
        div.onclick = function() {
            console.log('I was chosen');
        }
    </script>
</body>

1.4.4. Common mouse events

1.4.5. Analyze the three elements of the event

  • Three elements of pull-down menu

  • Close three elements of advertisement

1.5. Operation elements

The DOM operation of JavaScript can change the content, structure and style of web pages. We can use DOM operation elements to change the content, attributes and so on. (Note: these operations are implemented through the attributes of the element object)

1.5.1. Change element content (get or set)

innerText changing element content

<body>
    <button>Display current system time</button>
    <div>Some time</div>
    <p>1123</p>
    <script>
        // When we click the button, the text in the div changes
        // 1. Get element 
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // 2. Registration events
        btn.onclick = function() {
            // div.innerText = '2019-6-6';
            div.innerHTML = getDate();
        }
        function getDate() {
            var date = new Date();
            // Let's write a Wednesday, May 1, 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 + 'year' + month + 'month' + dates + 'day ' + arr[day];
        }
    </script>
</body>

The difference between innerText and innerHTML

  • Differences in getting content:

innerText removes spaces and line breaks, while innerHTML preserves them

  • Differences in setting content:

innerText does not recognize html, but innerthtml does

Case code

<body>
    <div></div>
    <p>
        I am character.
        <span>123</span>
    </p>
    <script>
        // The difference between innerText and innerHTML 
        // 1. innerText does not recognize html tags. Nonstandard spaces and line breaks are removed
        var div = document.querySelector('div');
        // Div.innertext = '< strong > today is: < / strong > 2019';
        // 2. innerHTML identifies html tags. W3C standard keeps spaces and newlines
        div.innerHTML = '<strong>Today is:</strong> 2019';
        // These two attributes are readable and writable. You can get the contents of the element
        var p = document.querySelector('p');
        console.log(p.innerText);
        console.log(p.innerHTML);
    </script>
</body>

1.5.2. Attribute operation of common elements

Get the value of the property

Element object. Attribute name

Set the value of the property

Element object. Attribute name = value

Case code

<body>
    <button id="ldh">Lau Andy</button>
    <button id="zxy">Jacky Cheung</button> <br>
    <img src="images/ldh.jpg" alt="" title="Lau Andy">
    <script>
        // Modify element attribute src
        // 1. Get element
        var ldh = document.getElementById('ldh');
        var zxy = document.getElementById('zxy');
        var img = document.querySelector('img');
        // 2. Register event handler
        zxy.onclick = function() {
            img.src = 'images/zxy.jpg';
            img.title = 'Zhang Xueyou Simida';
        }
        ldh.onclick = function() {
            img.src = 'images/ldh.jpg';
            img.title = 'Lau Andy';
        }
    </script>
</body>

1.5.3. Case: time sharing greetings

1.5.4. Attribute operation of form element

Get the value of the property

Element object. Attribute name

Set the value of the property

Element object. Attribute name = value

There are some attributes in the form element, such as disabled, checked and selected. The values of these attributes of the element object are Boolean.

Case code

<body>
    <button>Button</button>
    <input type="text" value="Input content">
    <script>
        // 1. Get element
        var btn = document.querySelector('button');
        var input = document.querySelector('input');
        // 2. Register event handler
        btn.onclick = function() {
            // The value text content in the form is modified by value
            input.value = 'Clicked';
            // If you want a form to be disabled, you can't click disabled. We want this button to be disabled
            // btn.disabled = true;
            this.disabled = true;
            // this refers to the caller btn of the event function
        }
    </script>
</body>

1.5.5. Case: imitating JD to display password


1.5.6. Style attribute operation

We can modify the size, color, location and other styles of elements through JS.

Common ways

Mode 1: by operating the style attribute

The style attribute of the element object is also an object!

Element object. style. style attribute = value;


Case code

<body>
    <div></div>
    <script>
        // 1. Get element
        var div = document.querySelector('div');
        // 2. Register event handler
        div.onclick = function() {
            // The attributes in div.style are named by hump 
            this.style.backgroundColor = 'purple';
            this.style.width = '250px';
        }
    </script>
</body>

Case: Taobao Click to close QR code

Case: cycle sprite background

Case: Show hidden text box content

Mode 2: by manipulating the className property

Element object. className = value;

Because class is a keyword, all use className.

Case code

<body>
    <div class="first">text</div>
    <script>
        // 1. Use element.style to get the modified element style if the style is less or the function is simple
        var test = document.querySelector('div');
        test.onclick = function() {
            // this.style.backgroundColor = 'purple';
            // this.style.color = '#fff';
            // this.style.fontSize = '25px';
            // this.style.marginTop = '100px';

            // 2. We can change the style of an element by changing its className, which is suitable for situations with many styles or complex functions
            // 3. If you want to keep the original class name, we can do so many class name selectors
            // this.className = 'change';
            this.className = 'first change';
        }
    </script>
</body>

Case: password box format prompt error message


1.6. Summary today

olor = '#fff';
// this.style.fontSize = '25px';
// this.style.marginTop = '100px';

        // 2. We can change the style of an element by changing its className, which is suitable for situations with many styles or complex functions
        // 3. If you want to keep the original class name, we can do so many class name selectors
        // this.className = 'change';
        this.className = 'first change';
    }
</script>
```
76 original articles published, 35 praised, 10000 visitors+
Private letter follow

Keywords: Attribute Javascript Programming C

Added by djetaine on Wed, 19 Feb 2020 12:01:31 +0200