preface

According to the moOCs “Quick Handling of front-end technology and matching big factory interview requirements” course organized by the topic, updated. If you think you’ve got it covered, check out my previous posts on this topic

Take interview questions often

1. What data structure is DOM?

DOM tree, tree structure

  • The DOM is essentially a tree, a tree parsed in HTML

2. Common APIS for DOM manipulation

This is only a list of instructions, not a specific display of API usage, reference from JavaScript manipulation OF the DOM commonly used API, you can read this article to learn the specific usage

2.1 the Node

  • Element provides access to Element tag names, child nodes, and attributes. Common HTML elements such as div, SPAN, and A tags are elements of this type
  • Text represents the Text node, which contains plain Text content. It cannot contain HTML code, but can contain escaped HTML code
  • Comment represents a Comment in an HTML document
  • Document stands for Document. In the browser, the Document object is an instance of HTMLDocument, representing the entire page. It is also a property of the Window object
  • DocumentFragment is the only type of node that does not have a corresponding tag. It represents a lightweight document and may serve as a temporary repository for nodes that might be added to the document

2.2 Node creation API

  • CreateElement creates an element by passing the specified tag name, or if the passed tag name is unknown, a custom tag is created
  • CreateTextNode creates a text node and accepts a single parameter, which is the text in the text node
  • CloneNode returns a copy of the node that called the method
  • “DocumentFragments” are DOM nodes. They are not part of the main DOM tree. The usual use case is to create a document fragment, attach elements to the document fragment, and then attach the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all of its child elements. Because the document fragment exists in memory, not in the DOM tree, inserting child elements into the document fragment does not cause page reflow (calculations of element position and geometry). Therefore, the use of document fragments is often used to optimize performance (see optimization below).

2.3 Page modification API

  • AppendChild we have used several times before to add the specified node to the end of the child element of the node calling the method
  • InsertBefore is used to add a node before a reference node
  • RemoveChild removes the specified child node and returns
  • ReplaceChild is used to replace one node with another

2.4 Node query API

  • The document.getelementById interface is simple. It returns an Element based on its ID, the value of which is of type Element, or null if it does not exist
  • Document. The getElementsByTagName to return a collection includes all the elements of a given tag name HTML HTMLCollection. The entire file structure is searched, including the root node. The returned HTML collection is dynamic, meaning it can update itself automatically to keep it in sync with the DOM tree
  • Document. The getElementsByName is mainly by specifying the name attribute to obtain element, it returns a NodeList object in real-time
  • Document. The getElementsByClassName this API is based on the element class returns a HTMLCollection in real-time
  • Document. querySelector returns the first matched element, or null if there is no matched element
  • Document. QuerySelectorAll returns all of the matched elements, but also can match multiple selectors

3. Difference between Attribute and Property

  • Property: modify the js internal variable form, by manipulating the form of the property of the object, does not affect the tag, will not be reflected in the HTML structure (try to use this)
  • Attribute: Modify the HTML attribute, which can be used to manipulate custom attributes. The tag will have the “attribute” you set. You can modify the inline style, and change the HTML structure
  • Both of the above can cause DOM re-rendering, but we should try to use property, because property can avoid unnecessary DOM rendering, while using attribute can change the HTML structure, cause DOM re-rendering, and consume unnecessary performance resources
  • Take a look at the front end of this article: Attribute VS Property

Style is as follows

<style>
    .container {
        border: 1px soild #ccc
    }

 .red {  color:red  } </style> Copy the code

The HTML structure is as follows

<div id="div1" class="container">
  <p>A paragraph 1</p>
  <p>A paragraph 2</p>
  <p>A paragraph 3</p>
</div>
// Get the p node const pList = document.querySelectorAll('p') const p1 = pList[0] Copy the code

① Property modification style

p1.style.height = '200px'
console.log(p1.style.height)
p1.className = 'red'
console.log(p1.className)
Copy the code

Watch for changes to the page and console output. As you can see, the style of the page has been changed ② Attribute modification style

// Customize the tag attributes
p1.setAttribute('data-name:'.'immoc')
console.log( p1.getAttribute('data-name:'))// set, get
p1.setAttribute('style'.'font-size:50px; ')
console.log( p1.getAttribute('style'))Copy the code

Observe changes to web pages, HTML tags, and console output. You can see that the font size has changed and there is an extra labelCustom attributes

4. How to consider performance when multiple DOM nodes are inserted at one time

DOM performance? How to optimize?

  • DOM manipulation is “expensive”, and expensive means performance, so avoid frequent DOM manipulation
  • Cache DOM queries
  • Change frequent DOM operations to one-time operations

4.1 DOM query optimization

(1) DOM query results are not cached, and frequent DOM queries consume performance

for(let i = 0 ; i<document.getElementsByTagName('p').length; i++){
     // A problem is that each loop evaluates (length) and DOM queries are frequently performed
}
Copy the code

② Cache DOM query results, only need to query once

const plist = document.getElementsByTagName('p') const length = plist.length for(let i = 0 ; i<length ; I++) {// only one DOM query is performed, saving performance}Copy the code

4.2 DOM insertion optimization

① Create 10 lists and perform DOM insertion at the end of each list

const list = document.getElementById('list')
for(let i = 0 ; i<10 ; i++){
    const li = document.createElement('li')
    li.innerHTML = `List item ${i}`
    list.appendChild(li)
} // For each DOM insert, a total of 10 DOM inserts are performed Copy the code

② Change frequent operation to one-time operation

const listName = document.getElementById('list')
// Create a document fragment that has not yet been inserted into the DOM tree
const frag = document.createDocumentFragment()
for(let j = 0 ; j<10 ; j++){
    const li = document.createElement('li')
 li.innerHTML = "list item" + j  frag.appendChild(li) } // Insert all 10 lists into the DOM tree after they are created Copy the code

5. How do I identify the type of browser

UserAgent The user-agent information for the browser, where the userAgent property is a read-only string that declares the value of the browser’s user-agent header for HTTP requests

const ua = navigator.userAgent
const isChrome = ua.indexOf('Chrome')
console.log(isChrome)
Copy the code

This judgment is far from enough, it is just a simple judgment, the specific judgment should be based on different browsers to make different recognition judgment

6. Analyze and disassemble parts of the URL

The Location object contains information about the current URL

  • Location. hash Sets or returns the URL (anchor) starting with the hash sign (#)
  • Location. host Sets or returns the host name and port number of the current URL
  • Location. hostname Sets or returns the hostname of the current URL
  • Location. href sets or returns the full URL
  • Location. pathName Sets or returns the path portion of the current URL
  • Location. port Sets or returns the port number of the current URL
  • Location. protocol Sets or returns the protocol for the current URL
  • Location. search sets or returns from question mark (?) Starting URL (query section)

7. Write a generic event binding (listening) function

7.1 Youth edition and usage

// <div>

// </div>

  function bindEvent( elem , type , fn ){
 elem.addEventListener( type , fn )  }   const btn1 = document.getElementById('btn1')   bindEvent( btn1 , 'click' , e => {  alert('clicked') })Copy the code

7.2 Full version of generic event binding functions (with proxy issues in mind)

function bindEvent( elem , type , selector , fn ){
    if( fn == null) {        fn = selector
        selector = null 
    }
 elem.addEventListener( type , e => {  let target = e.target  if( selector ){ // Proxy required  if( target.matches(selector) ){  fn.call( target , e )  }  } else {  fn(e) // No proxy is required  } })} Copy the code

8. Describe the flow of event bubbling

  • Microsoft’s IE presents a bubbling stream of events. What do I mean by event bubbling? We can think of it as a bubble at the bottom of the water. The bubble in the water will continue to rise until it comes to the surface. Event bubbling is something like this bottom-up process, where the event starts at the innermost element and goes all the way up to document

As an example, events occur in the order p -> div -> body -> HTML -> document

<div id="a1">
    <p id="a2"></p>
</div>
Copy the code

Event bubble based on the DOM tree structure, events will bubble up the trigger element, the application scenario is the event proxy

9. Normal binding and event broker binding

HTML structure

<body>
  <div id="div1">
      <p id="p1">The activation</p>
      <p id="p2">cancel</p>
 <p id="p3">cancel</p>  <p id="p4">cancel</p>  </div>   <div id="div2">  <p id="p5">cancel</p>  <p id="p6">cancel</p>  </div> </body> Copy the code

Simple event binding

function bindEvent( elem , type , fn ){
    elem.addEventListener( type , fn )
}
Copy the code

9.1 Common Binding

Click P1 to trigger the binding method (p1 activation pops up), then if I want P2, P3, P4… If they all bind to that method, don’t I have to bind them one by one? At this point we should consider the possibility of using event bubbling for event proxy, see below

const p1 = document.getElementById('p1')
bindEvent( p1 , 'click' , e => {
    // e.stopPropagation()
    // Comment this line to experience the event bubbling and prevent bubbling
    alert('p1 activation')
})Copy the code

9.2 Event proxy Binding

Because if you click P1, P2, p3, p4, p5, p6, it will bubble up to the body, meaning that if you click P1, P2, p3, p4, p5, p6, you will click on the element under the body, so we can do the proxy like this, just bind the method to the body

const body = document.body
bindEvent( body , 'click' , e => {
    alert('the body to activate')
})Copy the code

If, in the whole example, p1 is bound to 9.1 and body to 9.2, then when you click p1, it will pop up first, then the body will pop up again, so that you can feel the bubbles. If you uncomment e.topPropagation (), If you click p1 again, you’ll see that only the p1 activation pops up, not the body activation, because it stops bubbling

At the end of the article

If you think my writing is good, you can give me a thumbs up. If there is anything wrong or bad, please comment and point out so that I can correct it.

Other articles

  • ③ Asynchronous (Interview scenario)
  • Front End Basics ② — Scopes and closures
  • Front end basic knowledge ① — CSS interview questions
  • Gluten series ① — Didi SP side interview question
  • Gluten series ② — Didi intern cool the meridian

This article is formatted using MDNICE