Search code examples
javascriptjquerywrapall

Jquery wrap set of elements with open and close tag


I have set of different elements, for example:

<section class="box-1"></section>
<section class="box-2"></section>
<section class="box-3"></section>

I would like to wrap all those 3 elements with div + class so it looks like this:

<div id="new">
<section class="box-1"></section>
<section class="box-2"></section>
<section class="box-3"></section>
</div>

I tried the wrap, wrapAll, before, after and much more methods in jQuery, but none worked.

all those methods add <div id="new">, but immediately close the div like so:

<div id="new"></div>
<section class="box-1"></section>
<section class="box-2"></section>
<section class="box-3"></section>
</div>

All I need is a method to add OPEN div only before:

<div id="new">

and close div after the last element:

</div>

Solution

  • Use .wrapAll() to wrap the divs. What you use to identify which divs to wrap will depend on what else is on the page. If they are the only sections on the page, then $( "section" ).wrapAll( "<div class='new' />"); will achieve what you want. If not, then add a common class to the sections, and use that to identify your divs, $( ".sel" ).wrapAll( "<div class='new2' />");.

    $('#button').click(function() {
        $( "section" ).wrapAll( "<div class='new' />");
    });
    
    
    $('#button2').click(function() {
        $( ".sel" ).wrapAll( "<div class='new2' />");
    });
    .new {
      border: 1px solid red;
      padding: 10px;
    }
    
    .new2 {
      border: 1px solid orange;
      padding: 10px;
    }
    
    .box {
      background-color: yellow;
      margin: 3px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <section class="sel box-1">box 1</section>
    <section class="sel box-2">box 2</section>
    <section class="sel box-3">box 3</section>
    
    
    <input type="button" id="button" value="Click Me" />
    
    <input type="button" id="button2" value="Click Me" />