Harshdeep
Harshdeep

Reputation: 5824

When do we compare DOM elements in JQuery

$('body > div').each(function() {
...
});

What functionality does comparing body > div provide?

This is a part of answer provided to this question Comparing DOM elements with jQuery . I want to do similar thing but I am not able to understand the functionality provided by comparing two DOM objects.

Upvotes: 2

Views: 151

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337570

The > CSS selector is not comparing, it is the child selector.

More information here

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

That's not a comparison. It's a child selector. What it does is this:

Selects all direct child elements specified by "child" of elements specified by "parent".

So if you have HTML like this:

<div>
    <span>A span</span>
</div>
<div>
    <p>
        <span>A span</span>
    </p>
</div>

Then $("div > span") will select the first span, because it's a child of a div, but it won't select the second, because that's a child of a p.

Note that removing the child selector, and using $("div span") will select both span elements, because that looks for span elements that are descendants of a div, not specifically children.

Upvotes: 4

Related Questions