3

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?

1
  • 1
    In your case html is a variable, so you have to use $(html).insertAfter( "#block-1"); (without quotes (as @Elentriel answered)) or use code like this $("<div>some html...</div>").insertAfter( "#block-1"); Commented Nov 15, 2015 at 21:56

3 Answers 3

5

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~

Sign up to request clarification or add additional context in comments.

1 Comment

But of course my pleasure :) Add this as accepted answer if it helped you
5

The native JavaScript approach would be this:

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

jQuery approach:

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

1 Comment

Plus one for native js:)
5

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.