tags:

views:

100

answers:

2

I have several divs that share a common class. If one of these divs do not have a child div, I want to hide the div. I can find the right div but I'm unable to hide it.

This is my code,

$(function() {

        if ($(".adRight.childen('div')").length == 0) {
            $(this).hide();

        }

    });

What should I use instead of (this)? this refers to the document and not the div the if-statement found.

+4  A: 

You're looking for:

$("div.adRight:not(:has(div))").hide();

Does how it reads.

Your original code confused selectors with functions (eg, .childen is treated as a class selector), and shows you need to read a little more before writhing jQuery code. Sorry.
Your if statement, for example, is looking for something jQuery cannot find (wrong syntax). jQuery returns an empty collection - it has a policy not to throw unneeded exceptions, so its length is 0. It does not look for 0 children.
Also, note that for a simple action like hide you don't need to iterate the collection - hide will work with the elements you've already found, using your selector.

Kobi
Thank you Kobi! Very nice and efficient code. :)Have I understood this correctly,- div.adRight refers to all divs with class adRight?- :not and :has checks if it does not have a div?
Jova
Jova - correct. jQuery's selectors are very powerful, but easy to work with, and readable. You just have to find the right one!
Kobi
A: 

Maybe:

if ($(".adRight div")== undefined) { $(".adRight").hide(); }

(~~not sure)

Sam Zhou