Ho 在另一个

Ho check a <div> in another <div>

本文关键字:另一个 Ho      更新时间:2023-09-26
中检查一个

我需要检查具有特定 id 的<div>是否在另一个<div>中。我的 html 代码是:

<div class="box">
    ......
    <div id="home">
    </div>
</div>

我的Jquery代码是:

var div=$('div[class=box]');
div.each(function(id,element){
    if($(this).find(div).length>0){
        console.log("ENTER");
    }
});

我的目的是在具有特定类的<div>包含具有特定 ID 的另一个<div>时"做某事"。

你可以尝试找到它,并检查集合的长度

if ( $('.box #home').length ) { ...

查找具有元素的.box

var el = $('.box:has(#home)')

使用 .find('#home') 而不是像下面这样.find(div)

var div=$('div[class=box]');
div.each(function() {
    if($(this).find('#home').length>0){
        console.log("ENTER");
    }
});

只需使用类选择器(使用 . )和子选择器

if ( $('div.box #home').length > 0 )
{
   alert( "div exists" );
}
else
{
   alert( "div doesn't exists" );
}

试试这个

if($('div .box').find("div[id='home']").length > 0 ) {}
你可以

试试这个

if ($("div.box > #home").length > 0){
    console.log("ENTER");
   }

使用 jQuery 的.find()来查找你的div #home

if($("div.box").find("#home").length>0){
    alert("DIV FOUND");
}