如何检查元素是否没有div?

时间:2014-01-31 13:14:46

标签: javascript jquery

<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.childrenswrapAll个孩子。

这是我尝试过的(see this jsFiddle):

$(".container").find(".parent").each(function() {
    if(!$(".parent").find('.childrens').length){
        $(".parent").children().wrapAll("<div class='childrens'></div>");
    }
});

但不起作用。我做错了什么? 任何帮助表示赞赏!非常感谢你,抱歉我的英文不好!

8 个答案:

答案 0 :(得分:3)

您应该使用this分别引用每个父容器。将您的代码更改为:

$(".container").find(".parent").each(function() {
    if (!$(this).find('.childrens').length){
        $(this).children().wrapAll("<div class='childrens'></div>");
    }
});

http://jsfiddle.net/6PY29/3/

答案 1 :(得分:3)

没有必要。你可以使用not,has和wrapInner来解决它。

$(".container .parent").not(':has(".children")').wrapInner('<div class="childrens"></div>');

JSFiddle

另一种写作方式是

$(".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>");
}

Your updated fiddle


您必须在$(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>");
     }
});

http://jsfiddle.net/6PY29/2/

另外,你的小提琴没有在选项中选择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>");
  }
});