0

I am beginner webdeveloper. I have this code:

$(window).load(function () {
            $('.textowaTrescTresc img').each(function () {
                $(this).addClass('picla');
                console.log($(this));
            })
        })

This code add class to my images. It's work fine. I need add: data-label-class="label-class" to my images. In result I need:

<img src="garden.jpg" class="img-responsive picla" data-label-class="label-class" alt="Garden Design"/>

How can I make it? Please help me

trzew
  • 385
  • 1
  • 4
  • 13
  • 1
    Does this answer your question? [Adding data attribute to DOM](https://stackoverflow.com/questions/14935191/adding-data-attribute-to-dom) – ikiK Sep 12 '20 at 18:53
  • please use a newer version of `jquery`. the `load` function is removed in `jquery v3` – Sysix Sep 12 '20 at 18:57

1 Answers1

0

Try this one:

$(window).on('load',function () {
            $('.textowaTrescTresc img').each(function () {
                $(this).addClass('picla');
                $(this).data('label-class', 'label-value');
                console.log($(this));
            })
        })
Maksim Tikhonov
  • 770
  • 6
  • 15
  • `$(window).load..` is deprecated. Use `.on('load'` instead – charlietfl Sep 12 '20 at 18:55
  • thank you, but in this context it doesn't matter... The point is in `.data` method – Maksim Tikhonov Sep 12 '20 at 18:57
  • Also if he does not have data attribute he needs to create it with `attr`. Your answer wont work. ether cover all basis and even fix load as charlietfl mentioned. Or do not answer at all. Its a clear duplicate anyway. – ikiK Sep 12 '20 at 18:58
  • 1
    Of course it matters using deprecated methods in new answers. OP is new and should be advised properly – charlietfl Sep 12 '20 at 18:58
  • Something is wrong. Here is preview: http://serwer1356363.home.pl/_nauka/ In second photo I have description on image. I try add this description by this jQuery function, but it's not. working – trzew Sep 12 '20 at 19:03
  • @trzew all works fine: `Description 2` – Maksim Tikhonov Sep 12 '20 at 19:05
  • @MaksimTikhonov 0 look here: http://serwer1356363.home.pl/_nauka/ - only in first image I have label with description "Description". In next images it's something wring with. add. data-label-class – trzew Sep 12 '20 at 19:08
  • @MaksimTikhonov in 2.jpg, 5.jpg data-label is. not added – trzew Sep 12 '20 at 19:10
  • Apply `$('.textowaTrescTresc img')` selector and log it out to console to check your images are present in selection. – Maksim Tikhonov Sep 12 '20 at 19:14
  • I've found only 4 images. So, maybe it has bad definitions in class name – Maksim Tikhonov Sep 12 '20 at 19:15