jQuery 如何检查孩子是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3896982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if child exists
提问by Scarface
I have a div which could potentially have a hyperlink with an id of reply. How can I check if that a[id=reply]
exists? I thought it might be something like this but it alerts the message even if that hyperlink does not exist.
我有一个 div,它可能有一个带有回复 id 的超链接。我如何检查它是否a[id=reply]
存在?我认为它可能是这样的,但即使该超链接不存在,它也会提醒消息。
if($('div[chunk_id='+reply_chunk_id+']').children('a[id=reply]')){
alert('test');
}
回答by Nick Craver
Check the .length
of the selector to see how many elements it matched, in this case:
检查.length
选择器的 以查看它匹配的元素数量,在这种情况下:
if($("#reply").length) {
//child exists
}
However, it soundslike you have multiple elements with id="reply"
, which is invalid. Instead use class="reply"
and your selector will look like this:
但是,听起来您有多个带有 的元素id="reply"
,这是无效的。而是使用class="reply"
,您的选择器将如下所示:
if($("div[chunk_id='"+reply_chunk_id+"'] > a.reply").length){
//child exists
}
回答by darksioul
Another way to do it :
另一种方法:
if($("div[chunk_id="+reply_chunk_id+"]").children('.reply').length > 0){
// it exists
}