How to add class to the first img src="" of a set

1

Well, I have a set of <img src=“”> . I need, as soon as the page loads, add a class to the first of that set with Jquery , but remembering that they have a relative, href .

    ...
<a href="#">
    <img src=“” classe="SOMENTE AQUI">
</a>

<a href="#">
    <img src=“”>
</a>

<a href="#">
    <img src=“”>
</a>
    ....
    
asked by anonymous 08.07.2015 / 22:41

4 answers

4

It can be done this way:

$("a img").first().addClass('classe');
    
08.07.2015 / 22:45
3

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">
    
08.07.2015 / 22:42
3

You do not need jQuery to do this in modern browsers. I have to put an alternative with native JavaScript since nobody put ...

document.querySelector('a img').classList.add('novaClasse');

Example: link

    
09.07.2015 / 01:05
0

This was a perfect solution, because it facilitates when a reference div is placed:

$('#referencia img:first').addClass('classe');
    
08.07.2015 / 22:46