-4

I'm new to jQuery code, and recently saw a code like this:

var $pages = $('#main > div');

does that mean $pages will be the first div under #main or all the divs under #main? If I have the HTML code:

<div id="main">
    <div class="sub-div" id="1">1</div>
        <div id="1a">1a</div>
    <div class="sub-div" id="2">2</div>
    <div class="sub-div" id="3">3</div>
</div>

so, will $pages be an array contain all 3 divs or only the first one?

Additionally, can I use

var $pages = $('#main > div > div');

to get "1a" ?

Many thanks!

Duke Wang
  • 83
  • 3
  • 10
  • 1
    possible duplicate of [What does the ">" (greater-than sign) CSS selector mean?](http://stackoverflow.com/questions/3225891/what-does-the-greater-than-sign-css-selector-mean) – zerkms Dec 01 '14 at 22:24
  • This is the jQuery child selector - it selects direct descendants of the specified parent. So in this case, only the elements with class `sub-div` would be selected. http://api.jquery.com/child-selector/ – Ashley Strout Dec 01 '14 at 22:24
  • Have you read [any](http://api.jquery.com/) [documentation](http://api.jquery.com/child-selector/)? – Dominic Barnes Dec 01 '14 at 22:25
  • Try http://css.maxdesign.com.au/selectutorial/ to learn about CSS selectors – Paul Dixon Dec 01 '14 at 22:27

2 Answers2

0

It does the same thing as the CSS selector ">" It returns the children of an element that have the characteristic mentioned in the right hand part.

ex.

var $pages = $('#main > div');

Would return an array of all the divs which are children of the element with id "main"

therefore

var $pages = $('#main > div > div');

would return the divs that are children of the divs of the element with id "main".

Only one of the divs in pages has a child div and that is the div with id "1a"

Simba
  • 1,641
  • 1
  • 11
  • 16
0

$pages will be all immediate child divs of #main. If you have

<div id=main>
    <div id=1>
        <div id=2></div>
    </div>
    <div id=3></div>
    <div id=4></div>
    <span id=5>
        <div id=6></div>
    </span>
</div>

Then $('#main > div') will fetch 1, 3, and 4.

If you did $('#main div') then you're finding all matching descendants, not just immediate ones, so that would match 1, 2, 3, 4, and 6.

Paul
  • 646
  • 4
  • 13
  • in your case, if I have var $pages = $('#main > div'), then have var page1 = $pages[0] and var page2 = $pages[1], will "page1" fetch 1 and "page2" fetch 3? – Duke Wang Dec 02 '14 at 16:27
  • Yes, but using `$pages[number]` (or its equivalent, `$pages.get(number)`) will fetch a dom object as opposed to a jquery object. Using `$pages.eq(number)` will fetch a jquery object. Use whichever suits your purposes best! – Paul Dec 02 '14 at 16:35