Check if the item contains a specific child

I have many div that sometimes contain links. I want to check if they have a link. This is my attempt:

 var container = $(this).closest('.content').find('.text'); //Check if text contains a tags if(container+':has(a)'){ alert('contain link'); } else{ alert('no link found'); //Alert "contain link" even if no link is found. } 

By executing container.html() , I see the exact content of the container , including anchor tags, but my code above will always say that it cannot find the anchor tag.

Can someone tell me what I am doing wrong?

+7
javascript jquery dom html jquery-selectors
source share
4 answers

Change to this:

 if(container.find("a").length){ ... 

container is a jquery object, and .find() is a function of this object that finds elements in it. A length greater than 0 will mean that it will find the anchor mark and will be evaluated as true.

Edit:

Also, to explain why your example does not work. When you do container+':has(a)' , you do a string concatenation that runs toString() on your object (converting it to "[Object Object]"). Thus, you get the string "[Object Object]: has (a)", which will always be evaluated as true.

+8
source share

You can use the length property of the selector to determine if any elements were found. Try the following:

 var $container = $(this).closest('.content').find('.text'); if ($('a', $container).length) { alert('Contains links'); } else { alert('No links found'); } 
+1
source share

Change

 if(container+':has(a)'){ 

To

 if(container.has('a').size()){ 

container is a jquery object, not a selector string

+1
source share

Yours will work if you change it to

  if($(container+":has(a)").length > 0){ 

In documents

The stopwatch included in the delivery is checked for the descendants of matching elements.

0
source share

All Articles