user1333524
user1333524

Reputation: 463

Understand JQuery Selector expression

I am trying to read some JavaScript that is selecting element(s) using this expression

$("body > div:not(.layout-ignore):not(.ui-loader)") 

I get that its starting at the body but is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?

Can anyone explain to me this syntax? Also point me to some online documentation that helps me further understand this selector expression.

Cheers

Upvotes: 3

Views: 151

Answers (3)

voigtan
voigtan

Reputation: 9031

The body > div code is select all div that are direct children of body (http://devdocs.io/css/child_selectors)

<body>
    <div>first</div>
    <span>
        <div>second</div>
    </span>
</body>

(ignore that the html markup isn't valid here) but with that selector it will only select the div with the text first.

the :not selector will exclude everything within it: http://api.jquery.com/not-selector/

<body>
    <div>first</div>
    <span>
        <div>second</div>
    </span>
    <div class="example"></div>
</body>

body>div:not(.example) with the body>div it will select both the "first" div and the .example but will exclude .example div from the collection.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074028

...is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?

The > is saying that the div that matches must be an immediate child of body. It's called a "child combinator". So the only div elements that can possibly match are immediate children of body, they can't be inside another intermediate element. So:

<body>
    <div><!-- This div matches the selector -->
        <div><!-- But this div does not --></div>
    </div>
</body>

The two :not qualifiers (which are the "negation pseudoclass") are saying that the div cannot have the class layout-ignore and cannot have the class ui-loader.

So in total:

<body>
    <div><!-- This div matches the selector --></div>
        <div><!-- But this div does not, it's not a direct child of body --></div>
    </div>
    <div class="layout-ignore"><!-- This does not because it has layout-ignore --></div>
    <div class="ui-loader"><!-- And neither does this, because it has ui-loader --></div>
</body>

Upvotes: 3

Kyle Muir
Kyle Muir

Reputation: 3925

jQuery uses CSS selectors as its basis. The MDN has an extremely thorough guide as to what these are and how they work.

Please see here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors

and here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started

In your example it means any div (that is not of class .layout-ignore or .ui-loader) that is a child of body. Meaning nested divs would not be selected.

Hope this helps.

Upvotes: 4

Related Questions