当前位置:网站首页>DOM (document object model)

DOM (document object model)

2022-06-24 18:35:00 Brother Mengfan

Catalog

1、DOM What is it?

2、DOM Trees

3、 node

4、 Get elements  

4.1、 according to id obtain

4.2、 Get... According to the tag name

4.3、 according to name Property to get

4.4、 Get... According to the class name

4.5、 Get from selector

4.6、 obtain body Elements

4.7、 obtain html Elements

5、 Operational elements

5.1、 Change content

5.2、 Element attributes

5.3、 Form Elements

5.4、 Style elements

5.4.1、style

5.4.2、className attribute

5.5、 Operation properties 、

5.5.1、setAtrribute()

5.5.2、getAttribute()

5.5.3 removeAttibute()

5.5.4、 Custom properties

6、DOM event

6.1、 What is an event

6.2、 Elements of the event

6.3、 Common mouse event types


1、DOM What is it?

DOMDocument Object Model, Document object model ), Is used to present and interact with any HTML or XML Document interaction APIApplication Program Interface, Application program interface ).DOM Is the document model loaded into the browser , Represent the document in the form of node tree , Each node represents a component of the document ( for example : Page elements 、 String or comment, etc ).
DOM It is the most widely used on the world wide web API One of , It allows code running in the browser to access and interact with nodes in the file . Nodes can be created , Move or modify . Event listeners can be added to nodes and triggered when a given event occurs .
DOM It is not naturally regulated , It is the beginning of browser implementation JavaScript Only when . This tradition DOM Sometimes called DOM 0. Now? , WHATWG maintain DOM Existing standards .

2、DOM Trees

DOM Tree is also called document tree model , Map the document to a tree structure , It is processed by node objects , The result of processing can be added to the current page .
file : One HTML A page is a document , Use document Express

3、 node

Nodes are the most basic components of a web page , All content in a web page is a node in the document tree ( label 、 attribute 、 Text 、 Notes, etc. ), Use node Express
(1) Tag node : Also called element nodes , Refers to all the tags in the web page , Use element Express ;
(2) Attribute node : Refers to the attribute of the element node ;
(3) Text node : Refers to the content of the element node .

4、 Get elements  

Want to DOM To operate , First, you need to get the elements in the page , stay JavaScript in , There are several ways to get page elements .

4.1、 according to id obtain

Grammar format :var Element object = document.getElementById("id The attribute name ");
effect : Through the... Of an element in the page id Property to get the element object .
return value : This method will have a return value after execution , If obtained, the current object will be returned , Otherwise return to null.
Example :
    <div id="box"> This is a block </div>
    <script>
        var box = document.getElementById('box');
        console.log(box);
        console.log(typeof box);
    </script>

4.2、 Get... According to the tag name

Grammar format :var Return object set = document.getElementsByTagName(' Tag name ');
effect : Returns these objects according to the specified nominal name .
Example :
    <ul>
        <li> Beijing </li>
        <li> tianjin </li>
        <li> Shanghai </li>
        <li> Chongqing </li>
    </ul>
    <script>
        var lis = document.getElementsByTagName('li');
        console.log(lis);
    </script>
Except that it can be used document To reference this method , You can also use its parent group object to reference this method .
    <ul id="first">
        <li> Beijing </li>
        <li> tianjin </li>
        <li> Shanghai </li>
        <li> Chongqing </li>
    </ul>
    <script>
        //  Get the parent element  
        var ul = document.getElementById('first');
        console.log(ul);
        //  Get child elements from parent elements  
        lis = ul.getElementsByTagName('li');
        console.log(lis);
    </script>

4.3、 according to name Property to get

Grammar format :var Element object set = document.getElementsByName('name Property name ')
effect : according to name Property to get a collection of element objects .
Example :

    <p> <input type="checkbox" name="hobby" value=" music "> music 
        <input type="checkbox" name="hobby" value=" game "> game 
    </p>
    <script>
        var hobbies = document.getElementsByName('hobby');
        console.log(hobbies);
    </script>

4.4、 Get... According to the class name

Grammar format :var Element object set = document.getElementsByClassName(' Class name ');
effect : Get the element set according to the style name of the element ( That's the element class Property to get ).
Example :
    <div class="box">div1</div>
    <div class="box">div2</div>
    <script>
        var divs = document.getElementsByClassName('box');
        console.log(divs);
    </script>

4.5、 Get from selector

There are two ways to get the element object according to the specified selector : One is to obtain a single , One is to obtain multiple .
Get single object :var Element object = document.querySelector(' Selector name ');
Get multiple objects :var Element object = document.querySelectorAll(' Selector name ');
Example :
    <div id="box1"> Yes id Of div</div>
    <div class="box2"> Have a class style div</div>
    <div class="box2"> Have a class style div</div>
    <p> <input type="text" name="account" value="xian">
        <input type="radio" name="gender" value=" male "> male 
        <input type="radio" name="gender" value=" Woman "> Woman  </p>
    <script>
        //  Get from tag  
        var div = document.querySelector('div');
        console.log(div);
        var divs = document.querySelectorAll('div');
        console.log(divs);
        //  according to id obtain 
        div = document.querySelector('#box1');
        console.log(div);
        //  According to the class style  
        divs = document.querySelectorAll('.box2');
        console.log(divs);
        //  Get... According to the attribute selector  
        var gender = document.querySelectorAll('input[type="radio"]');
        console.log(gender);
    </script>

4.6、 obtain body Elements

Grammar format : document.body;
effect : obtain body All elements in
Example :

    <div class="box"></div>
    <input type="text" name="" id="">
    <h1>h1</h1>
    <script> 
        var body = document.body;
        console.log(body);
    </script>

4.7、 obtain html Elements

Grammar format :document.documentElement;
effect : Get the entire html Elements .
Example :
   <div class="box"></div>
    <input type="text" name="" id="">
    <h1>h1</h1>
    <script>
        var html = document.documentElement;
        console.log(html);
    </script>

5、 Operational elements

JavaScript Of DOM The operation can change the content of the web page 、 Structure and pattern , So you can use DOM Manipulate elements to change the contents of elements 、 Properties, etc .

5.1、 Change content

stay DOM To change the content of an element, you usually use the innerText and innerHTML Property to implement .

  Example :

    <div class="box">  This year is <strong>2022</strong> The first day of the year  </div>
    <script>
        // 1.  Get elements 
        var box = document.querySelector('.box');
        console.log(box);
        // 2.  Get the content of the element  
        // 2.1 innerHTML 
        var content = box.innerHTML;
        console.log(content);
        // 2.2 innerText 
        var content = box.innerText;
        console.log(content);
        // 3.  Set element content  
        // 3.1 innerHTML  distinguish htm label , Keep spaces and line breaks at the same time 
        box.innerHTML = '<font color="red"> This is a red word </font>';
        // 3.2 innerText  Don't recognize html label , Do not leave spaces and line breaks 
        // box.innerText = '<font color="red"> This is a red word </font>';
    </script>
innerHTML and innerText The same thing :
(1) Of innerHTML or innerText Property to get the contents of the object ;
(2) By giving objects innerHTML or innerText Attribute assignment can change the contents of an object .
innerHTML and innerText difference :

(1)innerHTML Property will put the html Execute after element parsing , and innerText Will not parse content Medium html Elements .

(2) If innerText Used to get the contents of the object , When the content contains html Element time , It will put This element has been deleted , and innerHTML Can't .
(3) If innerHTML Used to set the contents of the object , When the content contains html Element time , It will take these elements Set the object as it is ( Do not remove spaces and line breaks ), and innerText Will delete Spaces and line breaks .

5.2、 Element attributes

stay DOM in , Changing element attributes is done by Element object . Property name The way to achieve , It also has the function of reading and writing . Common attributes that elements can manipulate are :srchrefidalttitle And custom attributes .

  The demo case :

    <img src="1.jpeg">
    <script>
        var img = document.querySelector('img')
            //  obtain src attribute  
        console.log(img.src);
        //  modify src attribute  
        img.src = '2.jpeg';
        //  Add attribute  
        img.alt = ' picture ';
        img.title = ' Tips ';
        console.log(img);
    </script>

5.3、 Form Elements

stay Web In development , Forms are a common element , utilize DOM You can manipulate the attributes of the following form elements .

  These properties all have read and write operations , adopt Element object . Property name To get the element attribute value , adopt Element object . Property name = value To set the element attribute value . and checkedselected and disabled The value of an element attribute is of boolean type .

The demo case :

    <input type="text" name="name" value="123456"><br>
    <input type="checkbox" name=""><br>
    <select name="">
        <option value="">-- Please select --</option> 
        <option value=" Beijing "> Beijing </option> 
        <option value=" Shanghai "> Shanghai </option>
         <option value=" Chongqing "> Chongqing </option> 
        </select>

    <script>
        var input = document.querySelector('input')
            //  obtain type
        console.log(input.type);
        //  Set up type 
        //input.type = 'password'; 
        //  obtain value 
        console.log(input.value);
        //  Set up value 
        input.value = 'jock'
            //  obtain disabled 
        console.log(input.disabled);
        // false 
        //  Set up  disabled 
        input.disabled = true;
        //  Get elements  
        var ck = document.querySelector('[type="checkbox"]');
        console.log(ck);
        //  Get the selected state  
        console.log(ck.checked); // false 
        //  Set the selected state  
        ck.checked = true;
        //  Get the drop-down list 
        var sl = document.querySelector('select');
        console.log(sl);
        //console.log(sl[2]);
        var op = sl[2];
        console.log(op.selected);
        //  Settings are selected  
        op.selected = true;
    </script>

5.4、 Style elements

stay DOM Through JavaScript To change the size of the element 、 Color, position and other styles . Common ways are :

5.4.1、style

Example :
    <style>
        .box {
            width: 150px;
            height: 100px;
            background-color: blueviolet;
        }
    </style>

    <div class="box"></div>
    <script>
        //  adopt  JS  To change  div  Width and background color  
        var box = document.querySelector('.box')
            //console.log(box); 
            //  adopt  style  The way 
        box.style.width = '300px';
        box.style.backgroundColor = 'red';
    </script>
Be careful : If the style name contains a connector (-), Then the connector should be removed , At the same time, the following letters should be capitalized .

5.4.2、className attribute

Example :

  
<style>
        .box {
            width: 150px;
            height: 100px;
            background-color: blueviolet;
        }
        
        .bg {
            width: 200px;
            height: 200px;
            background-color: cornflowerblue;
        }
        
        .ft {
            color: white;
        }
    </style>

    <div class="box"> This is the text </div>
    <script>
        //  adopt  JS  To change  div  Width and background color  
        var box = document.querySelector('.box');
        console.log(box.className);
        box.className = 'bg ft'
    </script>

explain :

(1) Through object .className To get the style name of the current object ;

(2) Through object .className=' value ' You can style the current object .

5.5、 Operation properties 、

You can also set attribute values for attribute operations , You can also get the attribute value .

5.5.1、setAtrribute()

This method can set attributes for elements . Its syntax is as follows :

Object name .setAttribute(' Property name ', ' Property value ');

Example :
     <style>
        div {
            width: 100px;
            height: 30px;
            border: 1px solid #000000;
        }
        
        .bg {
            background-color: cornflowerblue;
            color: white;
        }
    </style>

  <div title=" This is a title, "> This is the content </div>
    <script>
        var div = document.querySelector('div')
            //  Set properties  
        div.setAttribute('class', 'bg');
        div.setAttribute('title', ' I changed the title ');
    </script>

5.5.2、getAttribute()

This method is used to get the value of the specified attribute name in the object . Its syntax is as follows :
Property value = object .getAttribute(' Property name ') ;
Example :
    <div title=" This is a title, "> This is the content </div>
    <script>
        var div = document.querySelector('div')
            //  obtain title attribute  
            //console.log(div.title); 
        var attrValue = div.getAttribute('title');
        console.log(attrValue);
    </script>

5.5.3 removeAttribute()

This method is used to delete the specified attribute in the object . Its syntax is :
object .removeAttribute(' Property name ');
Example :
    <div title=" This is a title, "> This is the content </div>
    <script>
        var div = document.querySelector('div');
        //  Delete title attribute 
        div.removeAttribute('title');
    </script>

5.5.4、 Custom properties

The purpose of custom attributes is to save and use temporary data , These data do not need to be obtained from the database . Custom attributes are created through setAttribute(' attribute ', ' value ') To set up , adopt getAttribute(' attribute ') To get .
Because some custom attributes are easy to cause ambiguity , It is not easy to determine whether it is a built-in attribute or a custom attribute of an element , To solve this problem ,H5 The user-defined attributes are specified in data- Start as the attribute name .
H5 The attribute definition method specified in can use getAttribute(' attribute ') Way to get , You can also use H5 New attribute acquisition method in .

  Example :

    <div data-index="1" data-list-name="jock"></div>
    <script>
        var div = document.querySelector('div');
        console.log(div.getAttribute('data-index'));
        div.setAttribute('data-title', ' title ');
    </script>

6、DOM event

6.1、 What is an event

The so-called event refers to some specific interaction moments in the document or browser window .JavaScript And HTML Interaction between It is achieved through events . about Web applications , Mouse click , Mouse movement , Pressing a key on the keyboard is an event . These corresponding operations will trigger the corresponding response mechanism for event processing .

6.2、 Elements of the event

For events , It contains three elements : Event source 、 Event types and event handlers .
(1) Event source : The element that triggered the event .
(2) Event type : What type of event was triggered , Such as clickmouseoverfocuskeyup etc. .
(3) Event handler : Program code to be executed after the event is triggered , Usually a function .
Example :
    <button id="btn"> Click I will trigger the event </button>
    <script>
        // 1.  Get elements 
        var btn = document.querySelector('#btn')
            // 1. Event source : This button is the event source  
            // 2.  Event type : This button will not trigger until it is clicked , Then its event type is click event  
            // 3.  Event handler  
        btn.onclick = function() {
            console.log(' You ordered me ');
        };
    </script>

6.3、 Common mouse event types

DOM There are many events , The most frequently used of these events is the mouse event , Common mouse events are shown in the following table .

  Example :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Common mouse event types </title>
    <style>
        .box {
            width: 150px;
            height: 100px;
            border: 1px solid #000000;
        }
        .bg {
            background-color: cornflowerblue;
        }
    </style>
</head>
<body>
<div class="box"></div>
<input type="text" id="account" value="123456">
<script>
    var box = document.querySelector('.box')
    //  Click events :onclick
    /*box.onclick = function () {
        console.log(' What do you want me to do ?');
    };
    //  Double-click the event :ondblclick
    box.ondblclick = function () {
        console.log(' Stop bugging me. .');
    };
    */

    //  Triggered when mouse passes :onmouseover
    box.onmouseover = function () {
        this.className = 'box bg';
    };
    //  Triggered when the mouse leaves :onmouseout
    box.onmouseout = function () {
        this.className = 'box';
    };
    //  Trigger when mouse moves :onmousemove
    box.onmousemove = function () {
        console.log(' Why do you touch me ');
    };

    var input = document.querySelector('#account')
    //  Triggered when the mouse focus is obtained :onfocus
    input.onfocus = function () {
        //console.log(this.value)
        this.style.backgroundColor = 'cornflowerblue';
    };
    //  Triggered when the mouse focus is lost :onblur
    input.onblur = function () {
        this.style.backgroundColor = '';
        console.log(this.value);
    };

    //  Triggered when the content of the text box changes :onchange
    input.onchange = function () {
        console.log(' The content has been modified ');
    };

    //  Triggered when the content of the text box is selected :onselect
    input.onselect = function () {
        console.log(' I don't want to be a cadre ');
    };
</script>
</body>
</html>
原网站

版权声明
本文为[Brother Mengfan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211333166889.html