jQuery insertAfter() not working as expected

263 views Asked by At

I'm trying to take #filters and all of it's contents and insert it after the in the following structure:

<div id = "top-level">

  <div id = "sub-level-1">
    <div class = "another-level">
      <div class = "last-level">
        <nav class = "nav-menu"></nav>
        <!-- insert #filters here -->
      </div>
    </div>
  </div>

  <aside>
    <div id = "filters"> 
      <div id = "filters-form">
        <div class = "more-contents"></div>
      </div>
    </div> 
  <aside>

</div>

Unfortunately, I can't get it to work as expected. It can't seem to "find" .nav-menu and insert it after, though I'm able to insert it after higher level elements.

// this works
var filters = $("#filters");
filters.insertAfter("#sub-level-1");

// doesn't work
var filters = $("#filters");
filters.insertAfter(".nav-menu");

Can anyone help?

1

There are 1 answers

6
Doug F On

I reworked it and got it to work. Keep in mind I put in some text just so I can inspect the elements easily.

var filters = $("#filters");
filters.insertAfter(".nav-menu");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "top-level">
  <div id = "sub-level-1">
    <div class = "another-level">
      <div class = "last-level">
        <nav class = "nav-menu">bbb</nav>
        <!-- insert #filters here -->
      </div>
    </div>
  </div>
  <aside>
    <div id = "filters"> 
      <div id = "filters-form">
        <div class = "more-contents">aaa</div>
      </div>
    </div> 
  </aside>
</div>

One edit I did was that your aside didn't have a closing tag, just two opening tags, so I fixed that.