Operation of DOM object / object oriented in JavaScript series

DOGIOOH 2020-11-13 01:49:48
operation dom object object oriented


JavaScript Operation of the series DOM object / object-oriented

01 operation DOM object

  • DOM : Document Object Model ( Document object model )

    because HTML After the document is parsed by the browser, it is a tree DOM Trees , To change the HTML Structure , It needs to pass JavaScript To operate DOM.


  • obtain DOM node

    • Operating a DOM Before the node , First get this DOM node . The most common methods are document.getElementById() document.getElementsByTagName(), as well as CSS Selectors document.getElementsByClassName().

    • document.getElementById() You can directly locate the only one DOM node .document.getElementsByTagName() and document.getElementsByClassName() Always return to a group DOM node . Choose... Precisely DOM, You can locate the parent node first , Then select from the parent node , To narrow down .

  • Node properties

    parentNode // Return the parent of the node
    childNodes // Returns the collection of child nodes
    childNodes[i]// Returns... In the collection of child nodes i Nodes
    firstChild// Returns the first child of the node , The most common use is to access the text node of the element
    lastChild // Returns the last child of the node
    nextSibling // Next node
    previousSibling// Last node
    
  • Element attributes

    firstElementChild // Returns the first child of the node , The most common use is to access the element
    The text node of element
    lastElementChild // Returns the last child of the node
    nextElementSibling // Next node
    previousElementSibling // Last node
    

  • to update DOM

    To get a DOM After node , We can update it .

    • There are two ways to update the text of a node :

      • modify innerHTML attribute , This is a very powerful way , Not only can you modify one DOM The text content of the node , It can also go directly through HTML Segment modification DOM The subtree inside the node .
      • modify innerText or textContent attribute , But this method can't set any HTML label .
    • to update CSS The way of pattern :

      • DOM Node style Property corresponds to all CSS, You can directly get or set .
      // Get the node first ele, Re pass style Property update CSS style
      ele.style.fontsize = '50px';
      

  • Insert DOM
    • Get one first DOM node , If it's time to DOM Node is empty , for example ,<div></div>, that , Use it directly innerHTML = <span>child</span> I can modify it DOM Content of node , amount to “ Insert ” New DOM node .
    • If this DOM Node is not empty , There are two ways to insert
      • A.appendChild(B), hold B Add nodes to A The last child of the node .
      • insertBefore( A,B ), hold A The node is inserted into B Before the node

  • establish DOM
    • createElement( tagName), Create a tag named tagName New element node of .

  • Delete DOM

    • To delete a node , First, we need to get the node itself and its parent node , then , Call the removeChild Cut yourself out .

      // Get the node you want to remove :
      var self = document.getElementById('to-be-removed');
      // Get the parent of the node to be removed :
      var parent = self.parentElement;
      // Delete :
      var removed = parent.removeChild(self);
      // matters needing attention : Although the deleted node is not in the document tree , But it's still in memory , Can be added to another location at any time .
      

  • Replace DOM

    • To replace a node , First, we need to get the node itself and its parent node , then , Call the replaceChild Replace yourself with .

      // Get the node you want to replace :
      var old = document.getElementById('to-be-replaced');
      // Get the parent of the node to be removed :
      var parent = self.parentElement;
      // Create a new node
      var new=document.createElement("img");
      // Set properties for new nodes
      new.setAttribute("src","images/f03.jpg");
      // Replace :
      parent.replaceChild(new,old);
      

02 object-oriented

JavaScript Don't distinguish the concept of classification and instance , It's through prototypes (prototype) To implement object-oriented programming .

  • Create objects

    • The way 1: adopt new Object();
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <script>
    // Create an object , adopt new Object();
    var person = new Object();
    // Set properties to objects object . Property name = Property value ;
    person.name = "John";
    person.age = 18;
    person.sex = ' male ';
    // Set methods for objects object . Method name = function(){};
    person.showName = function () {
    alert(this.name);
    };
    // Calling method
    person.showName();
    </script>
    </body>
    </html>
    
    • The way 2: Use curly braces
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <script>
    // Use curly braces to define an object
    // Be careful :
    //1. Assign values using colons
    //2. Multiple attributes are separated by commas
    //3. The last property or method does not need to be comma ;
    var student = {
    name:"John",
    age:20,
    sex:' male ',
    showName:function () {
    document.write(this.name)
    }
    };
    console.log(student);
    </script>
    </body>
    </html>
    
    • The way 3: Using constructors ( The first letter of the constructor must be uppercase )
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <script>
    // Use constructors to create multiple objects of the same type
    function person(name,age,sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.showName = function () {
    alert(this.name)
    }
    }
    var student1 = new person("John",23,' male ');
    var student2 = new person("Snow",24,' Woman ');
    var student3 = new person("Lily",25,' Woman ');
    console.log(student1);
    console.log(student2);
    console.log(student3);
    </script>
    </body>
    </html>
    

  • Prototype object

    • JavaScript A prototype will be set for each object created , Point to its prototype object .

    ​ When we use obj.xxx When accessing the properties of an object ,JavaScript The engine first looks up the property on the current object , If not found , Go to the prototype object , If you haven't found it yet , All the way up to Object.prototype object , Last , If you haven't found it yet , You can only return undefined.

    • Each function has one prototype attribute , This property is a pointer , You can point the prototype of an object to an object .

    • Take the code in create object mode 3 as an example , use new Person() The created object also gets a... From the prototype constructor attribute , It points to a function Student In itself , Its prototype chain is as follows :
    student1
    student2 -→ Person.prototype ----> Object.prototype ----> null
    student3
    
    • If we pass new Person() Created a lot of objects , Of these objects showName Functions actually only need to share the same function , This can save a lot of memory . To make the created object share a showName function , According to the property search principle of the object , All we have to do is put showName The function moves to student1student2 These objects can be on the same prototype , That is to say Person.prototype. Modify the code as follows :
    function person(name,age,sex) {
    this.name = name;
    this.age = age;
    this.sex = sex
    }
    }
    Person.prototype.showName = function () {
    alert(this.name);
    };
    

  • Prototype inheritance

    A prototype object is an instance of another prototype object . The related prototypes are progressive , It forms a chain of instances and prototypes , It's the prototype chain .

    JavaScript The way of prototype inheritance is :

    1. Define a new constructor , And use it internally call() Call hope “ Inherit ” Constructor for , And bind the this;
    2. With the help of intermediate functions F Implement prototype chain inheritance , It's best to go through packaged inherits Function completion ;
    3. Continue to define new methods on the prototype of the new constructor .

版权声明
本文为[DOGIOOH]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple