最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create wrapper div around two other divs with jQuery - Stack Overflow

programmeradmin3浏览0评论

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=".3.1/jquery.min.js"></script>
<div class="list-price">20000</div>
<div class="sell-price">10000</div>

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./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?

Share Improve this question edited Apr 19, 2019 at 16:21 double-beep 5,51019 gold badges40 silver badges48 bronze badges asked Aug 16, 2011 at 16:07 riskogabriskogab 631 gold badge1 silver badge3 bronze badges 1
  • your before and after usages are invalid as these methods do not write text to the document content, they rather write nodes. so, the 1st ('before') inserts the auto-closing (bu jQuery itself) tag, and the second ('after') skips due to invalid markup – Guard Commented Aug 16, 2011 at 16:32
Add a ment  | 

5 Answers 5

Reset to default 8

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 plete 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/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.

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

I had to revese your last line to:

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

发布评论

评论列表(0)

  1. 暂无评论