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')) {
...
}
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With