43
<div id="example">
  <div id="test"></div>
</div>

<div id="another">Blah</div>

I want to set $('#another').hide() but only if #example contains a child element called#test, is this possible? It seems like it would be.

5 Answers 5

88

Use length

if ($('#example').find('#test').length) {
    // found!
}
Sign up to request clarification or add additional context in comments.

Comments

9

I think what you are looking for is the following

if (jQuery.contains($('#example'), $('#test')) {
    $('#another').hide();
}

This might work as well, not sure off the top of my head.

if ($('#test', $('#example')).size() > 0) {
    $('#another').hide();
}

3 Comments

size(). Haven't seen that in a long time! length ftw.
Should 'contains' be called with a DOM element as parameter and not a jQuery object? api.jquery.com/jQuery.contains
Should this answer be updated to make use of "has()" as in: $('#test').has('#example') { $('#another').hide(); }
7

jQuery manual suggests to use:

if ($('#parent').has('#child').length) {
    //do something
}

http://api.jquery.com/has/

Comments

4
<script>
    var test = $('#example #test').length();
    if(test !== 0){
        $('#another').hide();
    }
</script>

2 Comments

test will never be undefined
length is not a function --> length. And it's also falsy so you can get rid of !==0 and just do if (test)
2

it's pretty simple.

$(document).ready(function(){
    if($('#example').children('#test').length > 0)
    {
        $('#another').hide();
    }
});​

http://jsfiddle.net/8rrTp/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.