[英]Detect an element inside a div using jQuery
What is the best way in your experience to detect the existence of an element inside a div? 检测div中元素是否存在的最佳方法是什么?
I'm currently using this: 我目前正在使用这个:
if (($('.parentDiv').width()) > 0){
//Do something
}
There has to be a more elegant way. 必须有一个更优雅的方式。
If empty means not even text nodes: 如果为空则表示不是文本节点:
if ($('.parentDiv').contents().length){
//Do stuff
}
or: 要么:
$('.parentDiv:not(:empty)') // which is nice...
.contents
docs : .contents
文档 :
Description: Get the children of each element in the set of matched elements, including text and comment nodes. 描述:获取匹配元素集中每个元素的子元素, 包括文本和注释节点。
if you care only of elements and not text nodes: 如果你只关心元素而不关心文本节点:
if ($('.parentDiv').children().length){
//Do stuff
}
Probably not what you want, but considering there's at least a little confusing over your requirements, you could consider if anything at all is within the container: elements, text, whatever. 可能不是你想要的,但考虑到你的要求至少有点混乱,你可以考虑是否有任何东西都在容器内:元素,文本,等等。
Say you have an empty div: 假设你有一个空div:
<div class="parentDiv"></div>
Then $(".parentDiv").html().length == 0
indicates its emptiness. 然后$(".parentDiv").html().length == 0
表示它的空虚。
If the div is not empty: 如果div不为空:
<div class="parentDiv"> </div>
<div class="parentDiv"><div></div></div>
Then $(".parentDiv").html().length
will indicate its occupiedness (returning 1 and 11, respectively, in those scenarios.) 然后$(".parentDiv").html().length
将指示其占用情况(在这些情况下分别返回1和11)。
If you wish to check only for elements, or specific elements, then $(".parentDiv").children()
would be the way to go. 如果你只想检查元素或特定元素,那么$(".parentDiv").children()
将是你要走的路。
使用children()
函数
$('.parentDiv').children()
if ( $( '.parentDiv' ).children().length > 0 )
{
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.