Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if child exists

Tags:

jquery

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');
}
like image 317
Scarface Avatar asked Oct 09 '10 16:10

Scarface


People also ask

How do you check if an element has a child?

Use one of the firstChild, childNodes. length, children. length property to find whether element has child or not. hasChildNodes() method can also be used to find the child of the parent node.

How do you check if an element has no children?

To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false . Whitespace and comments inside a node are also considered as text and comment nodes.

How do you check if an HTML element has a child?

HTML DOM Element hasChildNodes() The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.


2 Answers

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
}
like image 181
Nick Craver Avatar answered Sep 20 '22 18:09

Nick Craver


Another way to do it :

if($("div[chunk_id="+reply_chunk_id+"]").children('.reply').length > 0){
    // it exists
}
like image 41
darksioul Avatar answered Sep 19 '22 18:09

darksioul