jQuery insertAfter not working

Trung Tran picture Trung Tran · Jun 3, 2014 · Viewed 11.3k times · Source

I have a set of buttons:

  <div id="button">
      <button id="show_link_group">Show Links</button>
      <button id="show_contact_group">Show Contacts</button>
      <button id="show_update_group">Show Updates</button>
      <button id="show_activity_group">Show Action Items</button>
  </div>

And I am trying to insert my this div after it:

<div id="link_group">

      <p1>adsfadsf</p1>
</div>

It is supposed to insert after I click a button with id="show_link_group":

$('#show_link_group').click(function() {
  $("<div id='link_group'").after('<div id="button"></div>');
});

When I click it, it doesn't do anything. I followed this documentation:

http://api.jquery.com/insertafter/

What am I doing wrong??

thanks!

Answer

Barmar picture Barmar · Jun 3, 2014

You have to use a selector to specify where to insert, not an HTML string.

$("<div id='link_group'><p1>asdfasdf</p1></div>").insertAfter("#button");

if the link_group DIV is already in the DOM, you can do:

$("#link_group").insertAfter("#button");

This will move it from its current location to after the button.