0

I have a data attribute, data-no-lazy that I wanted to add to an img tag.

Before

<img class="lazyloading" src="image.png" />

After

<img class="lazyloading" src="image.png" data-no-lazy="1" /> 

How do I do that via jquery?

I looked online and I thought I had a solution. However, it didn't work.

<script>
    jQuery('.lazyloading').attr('data-no-lazy','1');
</script>

What should I do to add a data attribute?

Kristina Bressler
  • 1,642
  • 1
  • 25
  • 60

1 Answers1

0

At first I would test, if jQuery is present:

<script>
    console.log(jQuery); 
    // ... your code ...
</script>

Press F12 to show the console output in the browser debugger window.

If it is not present, make sure it is loaded, and that it is loaded before your js code is executed:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<script>
    // ... your code ...
</script>

And then make sure, that the document is loaded, before your code is executed:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<script>
    jQuery(document).ready(function(){
        // ... your code ...
    });
</script>

And after all that I would suggest to use the "data" function instead of the "attr" function:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<script>
    jQuery(document).ready(function(){
        jQuery('.lazyloading').data('no-lazy','1');
    });
</script>