如何检查孩子是否存在

时间:2021-07-26 00:03:30

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回复的超链接。如何检查[id = reply]是否存在?我认为它可能是这样的,但即使该超链接不存在,它也会提醒消息。

if($('div[chunk_id='+reply_chunk_id+']').children('a[id=reply]')){              
    alert('test');
}

2 个解决方案

#1


28  

Check the .length of the selector to see how many elements it matched, in this case:

检查选择器的.length以查看它匹配的元素数量,在这种情况下:

if($("#reply").length) {
  //child exists
}

However, it sounds like 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
}

#2


4  

Another way to do it :

另一种方法:

if($("div[chunk_id="+reply_chunk_id+"]").children('.reply').length > 0){
    // it exists
}

#1


28  

Check the .length of the selector to see how many elements it matched, in this case:

检查选择器的.length以查看它匹配的元素数量,在这种情况下:

if($("#reply").length) {
  //child exists
}

However, it sounds like 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
}

#2


4  

Another way to do it :

另一种方法:

if($("div[chunk_id="+reply_chunk_id+"]").children('.reply').length > 0){
    // it exists
}