The method of inserting a new element js insertAdjacentHTML

Here are a few of the new into the DOM API:

insertAdjacentText
insertAdjacentHTML
insertAdjacentElement

These three methods are used to insert html code structure of the text string format to a DOM element, and inserting DOM elements; usage of these three methods is basically the same.

insertAdjacentText(position, string);
insertAdjacentHTML(position, htmlstring);
insertAdjacentElement(position, element);

Wherein the parameter represents the position of the insertion position, string type, you can have the following values:

beforebegin
afterbegin
beforeend
afterend

The following structure may be used to describe the specific location:

<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->

Next, look at a Demo:
has the following DOM structure:

<div id="wrap">
    <div id="content">
        <p>origin test , test only</p>
    </div>
</div>
<script>
    window.onload = function () {
        var content = document.getElementById('content');
        content.insertAdjacentText('beforebegin', 'test beforebegin');
        content.insertAdjacentText('afterbegin', 'test afterbegin');
        content.insertAdjacentText('beforeend', 'test beforeend');
        content.insertAdjacentText('afterend', 'test afterend');
    }
</script>

After executing the above code, DOM structure as shown below:
image description

insertAdjacentHTML and insertAdjacentElement is similar.

Guess you like

Origin www.cnblogs.com/jlfw/p/12203782.html