Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element contains a specific child element

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?

like image 807
lomse Avatar asked Jul 31 '13 12:07

lomse


People also ask

How do you know if an element has a child element?

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 I check if a div has a child element?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

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

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.

like image 192
Dallas Avatar answered Oct 18 '22 11:10

Dallas


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');
}
like image 33
Rory McCrossan Avatar answered Oct 18 '22 11:10

Rory McCrossan