If you've already selected multiple elements, use first()
, as in the example:
$imgs = $('img');
$imgs.first().addClasse('classe');
If you want to select it just for this, pass as parameter in the selector, as in the example:
$('img:first').addClass('classe');
In this way, you "save time" by selecting only the element you want.
Note: If you only want to select elements that contain the src
attribute add [src]
to the selector, like this:
$('img[src]:first')
So you're saying that the src
attribute is mandatory 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><imgstyle="background:#999; width:200px; height:60px;">
<img src="http://placehold.it/200x60"><imgstyle="background:#999; width:200px; height:60px;">
<img src="http://placehold.it/200x60">