2015-09-27 52 views
0

我想選擇所有元素,除了第一個div在該類中。jquery:not(:first-child)wrapAll()each div

當前HTML:

<div class="cpt-cv-content-item"> 
    <a>...</a> 
    <h4>...</h4> 
    ... 
</div> 
<div class="cpt-cv-content-item"> 
    <a>...</a> 
    <h4>...</h4> 
    ... 
</div> 

我試着用保鮮所有:

$(".pt-cv-content-item :not(:first-child)").wrapAll("<div class='new'></div>"); 

此功能正確選擇除首先元素,但移動所有的人都進入第一個div。

我想是這樣的:

<div class="cpt-cv-content-item"> 
    <a>...</a> 
    <div class='new'> 
    <h4>...</h4> 
    ... 
    </div> 
</div> 
<div class="cpt-cv-content-item"> 
    <a>...</a> 
    <div class='new'> 
    <h4>...</h4> 
    ... 
    </div> 
</div> 

不幸的是我不能編輯HTML。 謝謝您提前

回答

0

包裝整個內容,然後將第一個孩子移出.new到主格。

使用wrapInner()包裹所有的孩子。使用prependTo()將元素移動到元素的開始位置。

$(".cpt-cv-content-item").wrapInner($("<div class='new'>")); 
 
$('div.new').each(function(){ 
 
    $(this).children().first().prependTo($(this).closest(".cpt-cv-content-item")); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="cpt-cv-content-item"> 
 
    <a>...</a> 
 
    <h4>...</h4> 
 
    ... 
 
</div> 
 
<div class="cpt-cv-content-item"> 
 
    <a>...</a> 
 
    <h4>...</h4> 
 
    ... 
 
</div>

1

使用wrap而不是wrapAll

$(".pt-cv-content-item :not(:first-child)").wrap("<div class='new'></div>"); 

wrap

描述:每一個的環繞元件周圍的HTML結構中匹配的元素。

wrapall

描述:線上纏繞在匹配的元素集合中的所有元素的HTML結構。

+0

換行功能包裝每個選定的元素,反正謝謝 –

0

我所選擇的所有元素在」 .PT-CV-內容項 ':

$(".pt-cv-content-item ").wrapInner("<div class='new'></div>"); 

我搬出在' .PT-CV-第一A HREF內容項」 DIV

$(".new a:first-child").each(function() { 
    $(this).parent().before(this); 
}); 

謝謝你們