This is the 24th day of my participation in the August More Text Challenge

Today we’re going to talk about insert tags, and the insert that we’re familiar with has innerHTML, but there are several methods that are similar to that, and we’re going to expand on that.

Insert tags

While most of the apis we’ve used have been for retrieving element content, the HTML5 specification defines a way to add content to a tag element.

innerHTML

InnerHTML inserts a string, comment, or text tag into the element, and it rerenders it into the DOM tree based on the content now provided, replacing all the nodes that the element previously contained.

<p id="username" data-name="jackson"> I'm Jackson < / p >const name = document.querySelector('#username');
    name.innerHTML = 'bear';
Copy the code

And here we can see that it’s actually replaced with bear, notice that it’s replaced, not added backwards.

outerHTML

OuterHTML replaces this element directly, and the new content replaces the old content

<p id="username" data-name="jackson"> I'm Jackson < / p >const name = document.querySelector('#username');
    let p = "

I am Big Bear G

"
; name.outerHTML = p; Copy the code

Here we see that the entire tag has been replaced.

InsertAdjacentHTML () and inserAdjacentText ()

Both methods take two arguments. The first argument is fixed and must be of one of the following four types

“Beforebegin”, inserts before the current element as the previous sibling node;

“Afterbegin”, inserted inside the current element as a new child node or placed before the first child node;

“Beforeend”, inserts inside the current element as a new child or after the last child;

“Afterend”, inserted after the current element as the next sibling node

Their second parameter is the same as the properties we need in innerHTML and outerHTML above, but let me write a notation here.

 // insert as the previous sibling node
name.insertAdjacentHTML("beforebegin"."

jackson!!!

"
); name.insertAdjacentText("beforebegin"."jackson!!!"); Copy the code

Our code example above is inserted as the previous sibling node. You can also see that my name is actually on the page.

Performance issues

Although this operation will be more convenient than we modify the content of THE HTML, but we modify the content if there are other binding JS events or operations, will lead to a large memory footprint, we must pay attention to the replaced element on the associated JS events.

Another rule is not to replace or add elements in a loop, which can take a lot of performance out of fetching and adding elements each time.

Cross site scripting

Cross-site scripting attacks must be mentioned here. For example, if we have an input box, which requires user input, there may be other criminals who enter , which may write some bad content to break our page program. When we use innerHTML, we must either escape or isolate the inserted data.