Scarface
Scarface

Reputation: 3913

How to check if child exists

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.

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

Upvotes: 20

Views: 73655

Answers (3)

Muhammad Awais
Muhammad Awais

Reputation: 1966

:has is also the other option along with length, for example if you want to get only those tr which has td in it

if($('tr:has(td)')) {}

Upvotes: 0

darksioul
darksioul

Reputation: 146

Another way to do it :

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

Upvotes: 6

Nick Craver
Nick Craver

Reputation: 630389

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

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:

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

Upvotes: 38

Related Questions