简体   繁体   中英

Correct way to append html to Jquery/Javascript

I have the following code:

<section class="section1">
    //Section one content
</section>
<section class="section2">
    <h4>Some Title</h4>

    <input type="hidden" class="keys" value="1"/>
    <div id="block-close-1"></div>
    <div class="block" id="block-1">
          //Block content
    </div>

</section>

<section class="section3">
    //Section3 content    
</section>

What I want to do is take some html and insert it after "block-1"

The HTML I wish to add looks like this:

    <input type="hidden" class="keys" value="2"/>
    <div id="block-close-2"></div>
    <div class="block" id="block-2">
          //Block content
    </div>

I have tried this:

var html = '//code as above';
$( "html" ).insertAfter( "#block-1");

The error I get is this:

Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.

I have also tried this: document.getElementById('#block-4').appendChild(html);

Error:

Uncaught TypeError: Cannot read property 'appendChild' of null

What is the correct way to add new HTML to the existing HTML?

You want $(html) not $("html")

The first tries to add the contents of the variable html, the second tries to find the tag html on the DOM and add it~

The native JavaScript approach would be this:

document.getElementById("block-1").insertAdjacentHTML("afterend",html);

jQuery approach:

$("#block-1").after(html);

From jQuery documentation for insertAfter ...

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

That is, if you want to place your new html after block-1 you select block-1 and call insertAfter() on it, passing the new html as the parameter -

$('#block-1').insertAfter( $(html) );

Or you could keep the order you have if it's more intuitive to you, but use .after()

$(html).after($('#block-1'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM