I am participating in the 2022 Spring Recruitment series of activities – experience review, click to view the details of the activity.

InsertAdjacentHTML (

The insertAdjacentHTML() method parses the text into an element and inserts the resulting node into the specified location in the DOM tree. It does not reparse the element it is using, so it does not destroy existing elements within the element. This avoids the extra serialization step and makes it faster than using innerHTML directly.

Above is the explanation given by MDN

Because I love this method, so I boldly Think:

InsertAdjacentHTML () is a method in Element’s API that converts string text into nodes where you want it and inserts it where you want it. And instead of replacing an existing node, as innerHTML does, it inserts it into the specified location.

Second, the use of

element.insertAdjacentHTML(position,text)

Parameters: the position

Position is the position you want to insert. There are four fixed values

  • 'beforebegin': the element element precedes itself.
  • 'afterbegin'Insert before the first child of the element element (always at the front, if I insert 5 nodes in order 1, 2, 3, 4, 5, then I insert 5 nodes in order 5, 4, 3, 2, 1).
  • 'beforeend'Insert the last child node of the element element element: insert the last child node of the element element element: insert the last child node of the element element element: insert the last child nodeAfter an existing nodeOh).
  • 'afterend'The element element comes after itself.

Position is a combination of two words and two parts to specify a position.

Before /after Before/on… The back gray line (the upper and lower boundaries of the box) can be used as a boundary. Before the boundary is before, and after is after

And then we have begin and end and that’s where we start, whether it’s on the inner node, whether it’s on the box. That’s where we start. Similarly, down here, whether it’s under the inner node, or under the box that’s where you end

Maybe it’s a little easier to remember

Parameters: the text

The second argument is the HTML statement that you want to insert, or XML, into the DOM tree, the DOMString can be a string, or it can be a new template string in ES6

Example 1

Implement a super simple effect of a parent box with 3 child boxes numbered 1,2, and 3

Create div nodes with JS and appEnd /appendChild in the parent box.

BUT NOW

Try using insertAdjacentHTML() with the js code below

Let root = document.querySelector(". Root ") Let STR = '<div class="box">${num}</div>' i < 3; i++) { root.insertAdjacentHTML("beforeend", ` <div class="box">${num}</div>`) num++; }Copy the code

Let’s try to change the position to afterbegin, but what if num numbers are still 1-3

Yes, it will become 3, 2, 1, as mentioned above, will be advanced but bottom effect

Where is the smell

I often use this method instead of using append() or appendChild() with innerHTML.

Use and difference between append and appendChild

Let’s first recall the roles and differences between Append () and appendChild()

Append () adds nodes Node and DOMString (mostly text) inside the parent element

AppendChild () can DOMString (mostly text) inside the parent element and inserts nodes with an error

It has two functions of the same, the difference is that one can insert nodes, the other can not insert nodes

For specific usage, please refer to other digger’s articles in the community

innerHTML

InnerHTML can also insert text, but it replaces existing Html, so it often requires += and is slightly less efficient because of the serialization process

Template string + insertAdjacentHTML()

You can also write Todolist, or add duplicate nodes, as shown in this whackmole example:

var holes = document.querySelector('.holes')
    var str = `<div class="hole">
                  <img src="img/mouse.png" class="mouse">
                  <img src="img/boom.png" class="boom" alt="">
                  <img src="img/hole.png" alt="">
               </div>`
    for (var i = 0; i < 9; i++) {
       holes.insertAdjacentHTML("afterbegin", str)
      }
Copy the code

In this way, I can quickly add each hole, and my mother will never have to worry about me going bald

And add elements Element. InsertAdjacentElement ()

Add a text Element. InsertAdjacentText ()

Performance issues

Be careful not to ask the user to enter text or HTML, as this will cause the HTML compiler to convert and performance will be low

Little mouse hole code

Attached is the complete code for Whack-a-Mole

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <meta http-equiv=" x-UA-compatible "content="ie=edge"> padding: 0; } .holes { width: 600px; height: 600px; margin: 10px auto; border: 1px solid #000; display: flex; flex-wrap: wrap; } .hole { width: 200px; height: 200px; outline: 1px solid red; position: relative; } .hole>img { width: 200px; height: 200px; position: absolute; } .hole>img.mouse { width: 150px; height: 150px; z-index: 2; top: 15px; left: 25px; display: none; } .hole>img.boom { z-index: 2; display: none; } .holes:hover { cursor: url('img/hammer.ico'), auto; } .holes:active { cursor: url('img/hammerdown.ico'), auto; } </style> </head> <body> <div class="holes"> </div> <script> window.onload = function() { var holes = document.querySelector('.holes') var str = ` <div class="hole"> <img src="img/mouse.png" class="mouse"> <img src="img/boom.png" class="boom" alt=""> <img src="img/hole.png" alt=""> </div>` for (var i = 0; i < 9; i++) { holes.insertAdjacentHTML("afterbegin", str) } var hole = document.querySelectorAll('.hole') var mouse = document.querySelectorAll('.mouse') console.log(holes);  function displayMouse() { var siteNum = Math.floor(Math.random() * 9) //console.log(siteNum, hole[siteNum]); hole[siteNum].querySelector('.mouse').style.display = 'block' } // setInterval(displayMouse, For (var I = 0; i < mouse.length; i++) { mouse[i].addEventListener('click', function() { var that = this that.style.display = 'none' that.nextElementSibling.style.display = 'block' setTimeout(function() { that.nextElementSibling.style.display = 'none' }, 1000) }) } } </script> </body> </html>Copy the code

Xiaobai daily learning records, welcome to guide the gods