jQuery - What am i doing wrong. if - else statements. wrap() if element is parent
Basic idea of my if else statements is this:
- If
.wrap
is parent element: do something - Else: do something else
This might not make much sense but if you look at the code here: http://jsfiddle.net/C6NQM/ ..it might
if( $('.wrap:parent'); )
{ $('.wrap').children().wrap('<div class="new" />'); }
else {开发者_运维问答 $('.wrap').wrap('<div class="new" />'); }
Things work separately if i remove if and else, so i came to the conclusion that there's something wrong with my if condition.
Any ideas about what's wrong here?
I think you want:
$('.wrap').each(function() {
if($(this).children().length > 0) {
$(this).children().wrap('<div class="new" />');
}
else {
$(this).wrap('<div class="new" />');
}
});
Updated fiddle.
Comments on your code:
if( $('.wrap:parent'))
will always evaluate to true
. A call to jQuery always returns a jQuery object. You could do if( $('.wrap:parent').length > 0)
, but even then you would select all elements in your example, as :parent
selects also nodes that have text nodes as children.
But even with that, the whole statement will work as follows: If there are any .wrap
elements that are parents, wrap their children in a new element. If not, wrap the elements themselves.
So it will not treat every .wrap
element individually.
Update: To cover every case (children, text content, empty), you probably have to do:
$('.wrap').each(function() {
if($(this).children().length > 0) {
$(this).children().wrap('<div class="new" />');
}
else if($(this).text().length > 0) {
$(this).html('<div class="new">' + $(this).text() + '</div>');
}
else {
$(this).wrap('<div class="new" />');
}
});
I tried and you code will work if you remove the ';' within the if condition.
Update:
PS: If you use jfiddle.net, general error in javascript will also be printed out in the error console of FireFox and Safari.
精彩评论