Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create wrapper div around two other divs with jQuery

How can I add an div element around 2 (or more) div? What I think:

$('div.list-price').each(function() {
  $(this).before('<div class="action-price">');
  $(this).next().after('</div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-price">20000</div>
<div class="sell-price">10000</div>

I hoped that above code will do this:

<div class="action-price">
  <div class="list-price">20000</div>
  <div class="sell-price">10000</div>
</div>

But:

<div class="action-price"></div>
<div class="list-price">20000</div>
<div class="sell-price">10000</div>

Can anybody help me?

like image 595
riskogab Avatar asked Aug 16 '11 16:08

riskogab


3 Answers

Try using the wrapAll function:

$('.list-price, .sell-price').wrapAll('<div class="action-price" />');
like image 125
DLL Avatar answered Nov 03 '22 22:11

DLL


You are thinking of the elements as HTML code, but they are objects. You can't add the starting and ending tag separately, because they are not complete elements.

Add the new element, and move the existing divs inside it:

$('div.list-price').each(function() {
  var newDiv = $('<div/>').addClass('action-price');
  $(this).before(newDiv);
  var next = $(this).next();
  newDiv.append(this).append(next);
});

Demo: http://jsfiddle.net/Guffa/eFXbN/1/

like image 1
Guffa Avatar answered Nov 03 '22 20:11

Guffa


A nice approach to this is to do the following.

$("div.list-price").each(function(){
     $(this).nextUntil("div.list-price").andSelf().wrapAll("<div class='action-price'></div>");
});

Its simple and readable, probably the way the jQuery devs intended it to be written.

like image 1
Blowsie Avatar answered Nov 03 '22 22:11

Blowsie