Reputation: 307
I need to wrap a div around content only if it is the last-child. The problem I have with this code is that it will execute if there is only one item. So i want to know how I should check to use the :last-child only when there are mor than one children. If there is only one child. I do not want the div added. Here is my code:
$('div[class^="columns-"]').each(function(){
$(this).find('div[class^="column"]:last-child').each(function(i){
$(this).wrapInner('<div class="col-last" />');
});
});
Upvotes: 1
Views: 581
Reputation: 2273
try this
$('div[class^="columns-"]').each(function(){
if((this).children().length>1)
$(this).
find('div[class^="column"]:last-child').
each(function(i){
$(this).wrapInner('<div class="col-last" />');
});
});
children().length
this will give the no of child elements
Upvotes: 0
Reputation: 474
* + selector
selects only elements preceded by an element
:gt(0)
selects all elements that are not first
http://api.jquery.com/category/selectors/
Upvotes: 0
Reputation: 10658
This should work
$('div[class^="columns-"]').each(function() {
var children = $(this).find('div[class^="column"]');
if(children.length > 1) {
children.last().wrapInner('<div class="col-last" />');
};
});
Upvotes: 0
Reputation: 146191
You may try this using filter
$('div[class^="columns-"]').each(function(){
$(this).find('div[class^="column"]:last-child')
.filter(function(){ return $(this).parent().children().length > 1; )
.each(function(i){
$(this).wrapInner('<div class="col-last" />');
});
});
Upvotes: 1
Reputation: 1289
If it's the only child, it's also the first one so you can do:
$('div[class^="columns-"]').each(function(){
$(this).find('div[class^="column"]:last-child:not(:first-child)').each(function(i){
$(this).wrapInner('<div class="col-last" />');
});
});
This way you can have multiple sets of columns and still get only the last child of the sets with more than one column in them, i.e. if you have:
<div class="row-1">
<div class="columns-1"></div>
</div>
<div class="row-2">
<div class="columns-1"></div>
<div class="columns-2"></div>
<div class="columns-3"></div>
</div>
<div class="row-3">
<div class="columns-1"></div>
</div>
the selector will only affect .row-2 .columns-3
Upvotes: 3