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?
Try using the wrapAll function:
$('.list-price, .sell-price').wrapAll('<div class="action-price" />');
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With