Search code examples
javascriptjquerywrapall

How to wrap and re-order elements inside?


I am trying to wrap some elements with jQuery in a li element. My problem is that I want to switch the order they will be inside the li. Right now is li start - a - div - li end, but I want li start - div - a - li end.

How can I do this? I tried everything but it didn't work. Here is my current code:

$('a.top_link+div.sub').not(":first").each(function() {
  $(this).prev().andSelf().wrapAll('<li class="aaa">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="something.com" class="top_link">Something</a>
<div class="sub">Some other content..</div>

I want to wrap that and re-order the content to look like:

<li class="aaa">
  <div class="sub">Some other content..</div>
  <a href="something.com" class="top_link">Something</a>
</li>

The elements above are more than one, only the content is different (part of a menu).


Solution

  • This should work:

    $('a.top_link+div.sub').each(function () {
        $(this).insertBefore($(this).prev()).add($(this).next()).wrapAll('<li class="aaa">');
    });
    

    For each div.sub, the above code does:

    1. Move it to before the <a>
    2. Add the <a> to the collection
    3. Wrap both in an <li>

    Demo: http://jsfiddle.net/vjC3x/