Reputation: 1854
Does anyone know if it's possible to define a CSS selector that selects the first image within a div, but only if it's the first child within the div.
In jQuery I would use a comparison something like this...
if ($('#div img:first-child') == $('#div>*:first-child')) {
...
}
Upvotes: 10
Views: 30179
Reputation: 72261
By definition of "first-child", the selector (assuming your div
had an id
of div
)
#div img:first-child
already does that. First image of any div
is
div img:first-child
However, as BoltClock's answer points out, the child selector is needed if you may have img
elements nested deeper in the div
.
Upvotes: 15
Reputation: 723708
You don't need to do a comparison in jQuery if all you want to do is select that img
. Just combine your two selectors like so:
#div > img:first-child
This works in both jQuery and CSS.
Upvotes: 14