最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if an element contains a specific child element - Stack Overflow

programmeradmin8浏览0评论

I have many divs 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?

I have many divs 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?

Share Improve this question edited Jul 31, 2013 at 17:47 Smern 19.1k22 gold badges76 silver badges93 bronze badges asked Jul 31, 2013 at 12:23 lomselomse 4,1658 gold badges49 silver badges68 bronze badges 1
  • 3 container+':has(a)' What do you think the result of applying the + operator on operands that are an object and a string will be? – T.J. Crowder Commented Jul 31, 2013 at 12:26
Add a comment  | 

4 Answers 4

Reset to default 9

Change to this:

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

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 runs toString() 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.

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

var $container = $(this).closest('.content').find('.text');

if ($('a', $container).length) {
    alert('Contains links'); 
}
else {
    alert('No links found');
}

Change

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

To

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

container is an jquery object, not a selector string

Yours will work if you change it to

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

In docs

The supplied selector is tested against the descendants of the matching elements

发布评论

评论列表(0)

  1. 暂无评论