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

Asked

Viewed 140 times

1

Guys , I have a set of <img src=“”>. I need, once the page is loaded, to add a class to the first of that set with Jquery, but remembering that they have a relative, the href.

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

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

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

4 answers

4

It can be done this way:

$("a img").first().addClass('classe');
  • Thanks for the help! Very helpful your reply.

  • @Lollipop

3

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! This is valid!

3

You don’t 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: http://jsfiddle.net/ffnyyu92/

  • 1

    It’s a case for: Too Much jQuery ;)

  • @Zuul haha this link is very good! The "Related" to the side are not to lose tb...

  • Good, but not necessarily.

0

This was a perfect solution as it makes it easier when a reference div is placed:

$('#referencia img:first').addClass('classe');
  • Don’t add a new response with the same content, just mark the one that met you right. ;)

  • 1

    Shouldn’t be $('a:first img').addClass('classe'); because you’ll be getting the image that’s in the first <a>? Or isn’t that what you want?

  • 3

    @Kaduamaral probably already had the answer when he asked the question and just wanted a way to share, but the other answers came before he published his, hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.