JQuery selector - get divs that are parents of more than one div

I am trying to get all elements on a page that have multiple divs as children. For example, in the following code:

<div id="1">
    <div id="1a">
        <div id="1aa">

        </div>
        <div id="1ab">

        </div>
    </div>
    <div id="1b">

    </div>
</div>
<div id="2">
    <div id="2b">

    </div>
</div>

      

My function will return #1

and #1a

as they contain 2 child divs.

I've tried this:

$('div > div + div').css("border", "1px solid red");

      

But not only does this not work as desired, I also want it to apply when there are 5, 6, 7 / as many child divs as possible, assuming that is >=2

.

What's the best way to achieve this?

+3


source to share


3 answers


You can use .filter()

.



$('div').filter(function() {
    return $(this).children('div').length >= 2;
}).css('border', '1px solid red');

      

+6


source


On the other hand...

$("div:has(>div:eq(1))")

      

jsFiddle .



It would be helpful to add a comment to this selector to explain its purpose, as it does not immediately clear its intent.

It does not use standard CSS, so it cannot delegate directly to querySelectorAll()

. If you find this to be a performance issue, just split it up into chunks (perhaps with help filter()

to reduce collection).

+2


source


Maybe you want something like this: http://jsfiddle.net/aJSbA/

if ($('div:has(div)').length) { // this will check if div has child div elem
    $('div > div').css("border", "1px solid red"); // applies css to its direct child
}

      

0


source







All Articles