I have many div
s which sometimes contain links. I want check whether or not 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 doing container.html()
I can see the exact content of container
including anchor tags, but my code above will always say that it cannot find the anchor tag.
Could someone tell me what I am doing wrong?
Change
To
container is an jquery object, not a selector string
Yours will work if you change it to
In docs
You can use the
length
property of a selector to determine if any elements were found. Try this:Change to this:
container
is a jquery object and.find()
is a function of that object that finds elements within it. A length greater than 0 will mean it finds an anchor tag and it will evaluate to true.Edit:
Also, to explain why your example isn't working. When you do
container+':has(a)'
, you are doing a string concatenation which runstoString()
on your object (converting it to "[object Object]"). So you end up with the string "[object Object]:has(a)" which will always evaluate to true.