The front end of DOM

JavaScript language 2020-11-13 05:04:20
end dom


Summary of front-end knowledge points ——DOM

1. What is? DOM: Document Object Model

What is? : Specialized in manipulating the content of a web page API standard ——w3c
Why? : Unifies the different browser to operate the homepage content API standard
advantage : Almost all browsers 100% compatible

2.DOM Tree:

What is? : All contents in the web page are stored in a tree structure in memory
Each item in the web page ( Elements , Text , attribute , notes …), It's all a node object on the tree .
The only tree root node : document
Why? : The tree structure is the best structure to preserve the relationship between upper and lower levels

Node object : Node
Every item in the web page is DOM A node object on the tree :
All nodes have three properties :
nodeType: Node type

 when : As long as you determine the type of node
Include :
document 9
element 1
attribute 2
text 3
problem : The tag names of elements cannot be further distinguished

nodeName: The name of the node

 when : As long as the tag name of the element is further determined
—— May replace nodeType
Include :
document #document
element All uppercase tag names
attribute Property name —— Not commonly used !
text #text

nodeValue: Node values —— Not commonly used

 document null
element null
attribute Property value
text Text content

3. lookup : 4 Kind of :

1. The node can be obtained directly without searching :
document.documentElement html
document.head head
document.body body
document.forms[id/i] form

2. Search by node relationship :
when : If you've got a node . When you want to find the surrounding nodes .
Include : 2 Planting trees :

  1. Node tree : A complete tree structure that contains all the content in a web page
    2 The relationship between the big classes :
    1. Father and son : 4 Kind of :
    elem.parentNode elem Parent node
    elem.childNodes elem Direct child of
    elem.firstChild elem First direct child of
    elem.lastChild elem The last direct child node under
    2. brother : 2 Kind of :
    elem.previousSibling elem The previous sibling element of
    elem.nextSibling elem The last sibling element of
    problem : Disturbed by invisible empty characters !

2. Element tree : Tree structure with only element nodes
2 The relationship between the big classes :

  1. Father and son : 4 Kind of :
    elem.parentElement elem Parent element of
    elem.children elem The direct child element of
    elem.firstElementChild elem The first direct child element under
    elem.lastElementChild elem The last direct child element under

2. brother : 2 Kind of :

elem.previousElementSibling elem The previous sibling element of
elem.nextElementSibling elem The last sibling element of

In the future, just use DOM Operate web content , They all use the element tree
explain : The element tree is not a new tree , It's just a subset of the node tree

childNodes and children: Dynamic collection (live collection)
What is? : Do not actually store attribute values , Search again every time you visit the collection DOM Trees
optimal : First look for , Efficient ! Because you don't have to return full properties .
Lack of : Every time you visit the collection , Will search again DOM Trees , Reduce efficiency
Traverse :
Not good. : for(var i=0;i<children.length;i++){…}
good : for(var i=0,len=children.length;i<len;i++){…}

Traverses all descendant elements under the specified parent element : 2 Kind of :
1. recursive : 2 Step :
1. The definition function only traverses all direct child elements under the specified parent element
2. The same operation as the parent node is called for each direct child node
Depth first : When a node has both children and siblings , Always traverse child nodes first .
All child nodes are traversed , Just return to traverse the sibling node .
2. loop : 2 Step :
1. Define iterator :

 iterator : You can get the... Of each descendant element node in turn Special object
how :
establish : var iterator=document.createNodeIterator(
parent, NodeFilter.SHOW_ELEMENT, null, false
);

2. Loop call iterator , Get the next node object :

 var curr=iterator.nextNode()
Built in depth first traversal algorithm
If curr return null, Indicates the end of the traversal

3. Press HTML lookup : 4 Kind of :
1. Press id lookup :

var elem=document.getElementById("id")
Return value : An element
If we can't find a way back null!
emphasize : 1. Only in document On the call

2. Search by signature :

var elems=parent.getElementsByTagName(" Tag name ")
Return value : A collection of elements
If you can't find it, return an empty set
emphasize : 1\. Can be called on any parent element
2\. It's not just looking for direct child elements , And look for... In all descendants

3. Press name lookup :

var elems=document.getElementsByName("name")
Return value : A collection of elements
If you can't find it, return an empty set
emphasize : Only in document On the call

4. Press class lookup :

var elems=parent.getElementsByClassName("class")
Return value : A collection of elements
If you can't find it, return an empty set
emphasize : 1. Can be called on any parent element
2. It's not just looking for direct child elements , And look for... In all descendants
3. Just one of the elements class Name matching , You can find the element
emphasize : The returned sets are dynamic sets
problem : You can only search by one condition at a time
When the search conditions are complex , The steps are cumbersome
solve : Use a selector to find :
web Front end development live tutorial Q Group : 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

4. Use a selector to find :

1. Find only one that matches the criteria :

var elem=parent.querySelector(" Selectors ")
Return value : An element
If you can't find it , return null

2. Find multiple elements that match the criteria :

var elems=parent.querySelectorAll(" Selectors ")
Return value : A collection of elements
If you can't find it, return an empty set
Returns a non dynamic set : Actually store attribute values , Even if you repeatedly access the collection ,
It doesn't lead to repeated searches DOM Trees
emphasize : 1\. Can be called on any parent element
2\. The selector is only relative to the current parent element
3\. Selector compatibility , Subject to the compatibility of the current browser

despise : Press HTML The difference between finding and searching by selector :

1. Return value : Press HTML Search returns a dynamic set
Search by selector returns a non dynamic set
2. efficiency : First look for : Press HTML High search efficiency
Searching by selector is inefficient
3. Ease of use : Press HTML The search is cumbersome
Press the selector to find simple

summary : In the future , Only one condition can find the desired element , First press HTML lookup

 As long as the search conditions are complex , Select the selector to find

jQuery That's how you choose it

5. modify :

Content : .innerHTML .textContent .value
attribute : 3 Kind of :
1.HTML Standard attribute : 2 Kind of :
1. The core DOM: The original DOM API, Requires support for all structured documents

 optimal : Almost everything Lack of : tedious
Get attribute nodes : var attrNode=elem.attributes[i]
Get attribute value : attrNode.value
Actually, it can be done one step at a time : var value=elem.getAttribute(" Property name ")
Modify attribute values : elem.setAttribute(" Property name "," value ")
Remove properties : elem.removeAttribute(" Property name ")
Determine whether the specified attribute is included : elem.hasAttribute(" Property name ")

2.HTML DOM: Specialized operation HTML Content API

 To the core DOM Commonly used API Simplification of
optimal : Simple Lack of : Not everything
simplify : HTML DOM Put all standard attributes in advance , Encapsulated in the element object , You can use . Direct access .
such as :
Get attribute value : elem. Property name
Modify attribute values : elem. Property name =" value "
Remove properties : elem. Property name =""
Determine whether the specified attribute is included : elem. Property name !==""
special case : class attribute :
ES The internal properties are included in the object of class, Used to record the type name when the object is created .
HTML Of class Properties cannot exist at the same time
therefore : DOM: html Of class attribute , Renamed className
web Front end development live tutorial Q Group : 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

2. State properties : disabled selected checked
1. You can't use the core DOM modify : Because the value is bool type
2. Only use HTML DOM, hit . modify
3. Custom extended properties :
when : 2 Kind of :

 1\. Save custom data on elements
2\. Instead of other selectors , Used to find element binding events

how : 2 set :

 Out-of-service HTML DOM visit , Because it's not a standard attribute , Not packaged in advance DOM In the element object
1. Common property name + The core DOM
2. HTML5:
When defining properties : data- Property name =" value "
Get or modify property values : elem.dataset. Property name

Fixed usage : Replace other selectors with custom extended properties , Binding events for elements

 Why? :
id: only
class: Constant change
elem: Make an effect , Any element may be used
solve : In the future , As long as you bind an event to an element , Add custom extension attributes to the element first ,
Use custom extended attributes to find elements , The binding event
optimal : There is no limit to the number of , It doesn't change with style , Not limited by elements
how :
Definition : data- Property name =" value "
lookup : You can only use the property selector to find :[data- Property name = value ]

6. style : 2 Kind of :

1. inline style :

 modify : elem.style.css Property name
emphasize : 1. css Attribute names should be changed to humps
2. The length value must be added with px Company
obtain :
problem : Out-of-service elem.style.css Property name
reason : elem.style Contains only inline styles ! Cannot get styles in internal or external style sheets
solve : Get the calculated style !
The calculated style : The collection of all styles that are ultimately applied to the element
And the relative value is converted into absolute value
when : As long as you get the style , To get the calculated style
how : 2 Step :
1. Get the calculated style object :
var style=getComputedStyle(elem);
2. from style gain css Property value
var value=style.css Property value
emphasize : getComputedStyle Get styles are read-only !

2. Inside / external : 3 Step :
1. Get the stylesheet object :

var sheet=document.styleSheets[i];

2. Get the... In the stylesheet object cssRule

 What is? cssRule: Every... In the style sheet {} It's just one. cssRule
How to get : var rule=sheet.cssRules[i]

3. get cssRule Medium style Object's css attribute

var value=rule.style.css attribute

problem : use elem.style.css Only one attribute can be modified css attribute

 If you modify multiple attributes at the same time , The code will be cumbersome

solve : use class Batch apply styles
how : 2 Step :

  1. stay css Prepare all kinds of class
  2. Use procedure , In the corresponding case , Select corresponding class application !
    web Front end development live tutorial Q Group : 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

7. add to :

add to : 3 Step :

  1. Create an empty element
    var a=document.createElement(“a”);

2. Set the required properties
a.href=“http://tmooc.cn”;
a.innerHTML=“go to tmooc”;
3. Add new elements to DOM Trees :3 Kind of api:
parent.appendChild(a) take a Append to the end of the specified parent element
parent.insertBefore(a, child) take a Insert before the existing child element under the specified parent element
parent.replaceChild(a, child) use a Replace the existing child element under the specified parent element

Optimize : Minimize operation DOM The number of trees , Redraw to reduce rearrangement
Why? :
HTML Page loading process :
html -> DOM Tree

 ↓
Render Tree -> ***layout -> paint
↑

css -> cssRules
how :

  1. If you add both parent and child elements , It should be in memory first , Add all child elements to the parent element ,
    Finally, add the parent element to the page at one time

8. Delete :

Optimize : Minimize operation DOM The number of trees
Why? : Reduce rearrangement redraw
how : 2 Kind of :
1. If you add both parent and child elements , It should be in memory now , Add child element to parent element , Finally, the parent element is added to DOM Tree
2. If the parent element is already on the page , To add more than one level child element , Fragments should be used :

 What is a document fragment : The virtual parent element that temporarily stores multiple child elements in memory
when : As long as you add more than one level sub element to a web page at the same time , You can use document fragments
how : 3 Step :
1. Create a document fragment
2. Add child elements to the document fragment
3. Add the document fragment as a whole to DOM Trees

Delete : parent.removeChild(child)

 Usually : child.parentNode.removeChild(child)

9.HTML DOM Common objects :

Image: establish : var img=new Image();

Select: On behalf of a page select Elements
attribute :
.selectedIndex Get the current select Selected option The subscript position of
.value get select In the middle of option Value

 If you choose option No, value attribute , Then use innerHTML Instead of

.options Get the current select All of them option Set

 .options.length get select All of them option The number of
.options.length=0

.length => .options.length

 Clean all option .length=0

Method : .add(option) Add one more option

 problem : .add Document fragments are not supported
.remove(i) remove i Positional option

Option: representative select next option Elements
establish : var opt=new Option(text,value)
attribute : .text .value .index

Table: Representing one table Elements
Group the lines :
Create row groups : var thead=table.createTHead()

 var tbody=table.createTBody()
var tfoot=table.createTFoot()

Delete row group : table.deleteTHead()

table.deleteTFoot()

Get row groups : table.tHead table.tFoot table.tBodies[i]
Row grouping : In charge of :
add rows : var tr= Row grouping .insertRow(i)

 stay i Position inserts a new line
Fixed routine : 1\. Add a new line at the end : .insertRow()
2\. Insert a new line at the beginning : .insertRow(0)

Delete row : Row grouping .deleteRow(i) —— Not commonly used !

 problem : i The requirement is the relative subscript position within the current row group
Can't automatically get
It should be replaced by : table.deleteRow(tr.rowIndex)
tr.rowIndex Can automatically get the current line in the whole table Position in

Get row : Row grouping .rows[i]
That's ok : Take care of it
Add grid : var td=tr.insertCell(i)

 Fixed usage : Add a grid to the end of the line : tr.insertCell()
explain : Can only be created td, Can't create th

Delete the grid : tr.deleteCell(i)
Get the lattice : tr.cells[i]

Form: Representing one form Elements
obtain : var form=document.forms[i/id]
attribute : .elements Get a collection of all form elements in the form
web Front end development live tutorial Q Group : 767273102 , There are free development tools for rice , Zero basis , Advanced video tutorial , I hope novices don't take detours

 .elements.length Get the form , The number of form elements
.length => .elements.length

Method : .submit() Instead of submit Button , In the program to achieve manual submission form

Form Elements :
obtain : form.elements[i/id/name]

 More simplified : form.name

Method : .focus Make the current form element focus

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

  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