If you have already selected several elements, use first()
, as in the example:
$imgs = $('img');
$imgs.first().addClasse('classe');
If you want to select it only for this, pass as parameter in the selector, as in the example:
$('img:first').addClass('classe');
This last way, you "save time" by selecting only the element you want.
Obs.: If you want to select only elements containing the attribute src
add [src]
to the selector, thus:
$('img[src]:first')
So you will be saying that the attribute is mandatory src
and will only select the first one that has the attribute, for example:
$('img[src]:first').addClass('borda');
img{
border: 5px solid #FFF;
display:block;
}
.borda{
border-color:#87C9F8;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img style="background:#999; width:200px; height:60px;">
<img src="http://placehold.it/200x60">
<img style="background:#999; width:200px; height:60px;">
<img src="http://placehold.it/200x60">
Thanks for the help! Very helpful your reply.
– Lollipop
@Lollipop
– Ricardo