riskogab
riskogab

Reputation: 63

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?

Upvotes: 6

Views: 12186

Answers (5)

DLL
DLL

Reputation: 541

Try using the wrapAll function:

$('.list-price, .sell-price').wrapAll('<div class="action-price" />');

Upvotes: 8

Blowsie
Blowsie

Reputation: 40525

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.

Upvotes: 1

Eric
Eric

Reputation: 146

I had to revese your last line to:

$rest.wrap('').parent().append($first);

Upvotes: 0

Guard
Guard

Reputation: 6955

$first = ... // the 1st element
$rest = ... // other elements, may be just the second one
$first.wrap('<div class="wrapper"/>').parent().append($rest)

Upvotes: 0

Guffa
Guffa

Reputation: 700172

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/

Upvotes: 1

Related Questions