如何使用Javascript基于类名重新排序div

时间:2012-11-25 08:53:49

标签: javascript jquery

这是我的HTML

<div id="subscriptionContainer">

<div class="subscription">
  <div class="subs-btn">
        <div class="subscribed">Subscribed</div>
  </div>
</div>


<div class="subscription">
  <div class="subs-btn">
        <div class="btnGetit">Get It</div>
  </div>
</div>

<div class="subscription">
  <div class="subs-btn">
        <div class="subscribed">Subscribed</div>
  </div>
</div>


<div class="subscription">
  <div class="subs-btn">
        <div class="btnGetit">Get It</div>
  </div>
</div>

<div class="subscription">
  <div class="subs-btn">
        <div class="subscribed">Subscribed</div>
  </div>
</div>


<div class="subscription">
  <div class="subs-btn">
        <div class="btnGetit">Get It</div>
  </div>
</div>

</div>

现在我想重新安排带有“subscriptionContainer”的“订阅”div,以便将具有class =“subscribed”的div移动到底部,并且具有class =“btnGetit”的div应该全部向上移动。请在Javascript或JQuery中提供解决方案。

3 个答案:

答案 0 :(得分:7)

var $wrap = $('#subscriptionContainer');
$wrap.find('.subscribed').parents('.subscription').appendTo( $wrap );

演示: http://jsbin.com/ebudux/2/edit

答案 1 :(得分:0)

这是我最终制定的纯JavaScript实现

var container = document.getElementById('subscriptionContainer');
var allDivs = container.getElementsByTagName('div');
var subsProds = new Array();
var count = 0;

for (i = 0; i < allDivs.length; i++)
{
    var currentElement = allDivs[i];
    if (currentElement.className == 'subscribed') {
        subsProds[count] = currentElement.parentNode.parentNode;
        container.removeChild(currentElement.parentNode.parentNode);
        count++;
    }
}
for (i = 0; i < subsProds.length; i++)
    container.appendChild(subsProds[i]);

答案 2 :(得分:0)

var $wrap = $('#subscriptionContainer');
$wrap.find('.subscription').children('.subscribed').appendTo( $wrap );