Marťas
Marťas

Reputation: 1092

Are parentheses in jQuery or CSS selectors allowed?

On my page there are 2 parent DIVs: #div1 and #div2. Both can contain children DIVs. I need to select using jQuery all these children DIVs from both parents together.

<div id="div1">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div id="div2">
    <div></div>
    <div></div>
</div>

Is it allowed to write $("(#div1, #div2) > div") ?

I know, I can write $("#div1 > div, #div2 > div"), what is the same. But if the expression "> div" would be something much more complex, and I would have more parents, the expression would get unreadable.

Upvotes: 2

Views: 256

Answers (4)

Nick Caballero
Nick Caballero

Reputation: 944

You use the add and children functions:

$('#div1').add('#div2').children('div')

Upvotes: 0

xdazz
xdazz

Reputation: 160833

No, the expression is not valid.

You could do $("#div1, #div2").find('> div') instead.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Break it up into pieces

$("#div1, #div2").find("> div") 

Upvotes: 4

Justin Ethier
Justin Ethier

Reputation: 134167

You could assign the parent div's a class:

<div class="pdiv" id="div1">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="pdiv" id="div2">
    <div></div>
    <div></div>
</div>

and then use the selector over the class:

$(".pdiv > div")

This would be a cleaner solution if you have more than just a handful of parent div's.

Upvotes: 0

Related Questions