Raja
Raja

Reputation: 3618

Is there any difference between $("#item1 #item2") and $("#item1>#item2")?

I was reviewing code and found that

$("#item1 #item2") and $("#item1>#item2")

are used interchangeably. Is there any difference or is it one and the same?

Upvotes: 2

Views: 214

Answers (4)

Eric
Eric

Reputation: 97631

Both will match

<div id="item1">
    <div id="item2">
    </div>
</div>

But only the first one will match

<div id="item1">
    <div>
        <div id="item2">
        </div>
    </div>
</div>

The first expression uses the descendant selector. The > symbol in the second expression is the child selector. Both are standard CSS selectors.

However, since ids must be unique, both are overcomplicated. Instead, you should just use $('#item2')

Upvotes: 5

Orbling
Orbling

Reputation: 20612

> means the immediate, direct child.

Direct

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

Indirect

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

See the documentation: http://api.jquery.com/child-selector/

Upvotes: 0

Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 10467

The > sign means "include only elements that are direct children of that element". So if you want to select only the children being subnodes of #item1, use it, otherwise use first option.

Upvotes: 0

Chris Sobolewski
Chris Sobolewski

Reputation: 12955

The same as the CSS selectors

#this #that

means any #that that is a child of #this.

Where as

#this>#that

Means only #that which is a direct descendant of #this.

More reading on descendant selectors.

Upvotes: 1

Related Questions