<div class="parent" id="1">
<div class="childrens">
<p> etc... </p>
</div>
</div>
<div class="parent" id="2">
<p> etc... </p>
</div>
我想检查div.parent
是否不包含名为.childrens
的子元素,因此如果不在此div中添加div.childrens
和wrapAll
个孩子。
这是我尝试过的(see this jsFiddle):
$(".container").find(".parent").each(function() {
if(!$(".parent").find('.childrens').length){
$(".parent").children().wrapAll("<div class='childrens'></div>");
}
});
但不起作用。我做错了什么? 任何帮助表示赞赏!非常感谢你,抱歉我的英文不好!
答案 0 :(得分:3)
您应该使用this
分别引用每个父容器。将您的代码更改为:
$(".container").find(".parent").each(function() {
if (!$(this).find('.childrens').length){
$(this).children().wrapAll("<div class='childrens'></div>");
}
});
答案 1 :(得分:3)
没有必要。你可以使用not,has和wrapInner来解决它。
$(".container .parent").not(':has(".children")').wrapInner('<div class="childrens"></div>');
另一种写作方式是
$(".container .parent:not(:has(.children))").wrapInner('<div class="childrens"></div>');
您的代码的问题在于您再次重新选择所有.parent元素而不使用this
来处理当前在该迭代上引用的元素。您的代码需要看起来更像
$(".container").find(".parent").each(function() {
var currentParent = $(this);
if(!currentParent.find('.childrens').length){
currentParent.children().wrapAll("<div class='childrens'></div>");
}
});
答案 2 :(得分:1)
而不是.parent
使用this
$("#container").find(".parent").each(function() {
if(!$(this).find('.childrens').length) {
$(".parent").children().wrapAll("<div class='childrens'></div>");
}
});
答案 3 :(得分:1)
试试这个:
if(!$(this).find('.childrens').length){
$(this).children().wrapAll("<div class='childrens'></div>");
}
您必须在$(this)
次迭代中使用.each()
定位当前元素,然后使用它的className定位,该类名称会查找#container
中可用的所有类。
答案 4 :(得分:1)
在每个循环内部,您需要使用$(this)来引用当前的parent
元素。目前,您正在检查所有parent
元素:
$("#container").find(".parent").each(function() {
if(!$(this).find('.childrens').length){
$(this).children().wrapAll("<div class='childrens'></div>");
}
});
另外,你的小提琴没有在选项中选择jQuery,所以永远不会有效。
答案 5 :(得分:1)
我建议:
$('.parent').filter(function (){
return !$(this).find('.children').length;
}).each(function (){
$(this).contents().wrapAll('<div class="children"></div>');
});
答案 6 :(得分:0)
$(".container").find(".parent").each(function() {
var parent = $(this);
if(!parent.find('.childrens').length){
parent.children().wrapAll("<div class='childrens'></div>");
}
});
答案 7 :(得分:0)
使用:
$(".container").find(".parent").each(function() {
if(!$(this).find('.childrens').length){
$(this).children().wrapAll("<div class='childrens'></div>");
}
});