0

I am using this code to change the src attribute of an img element to data-src, but my current solution doesn't work. I don't know what I'm doing wrong.

Any help would be appreciated.

<script>    
  $("img").each(function() {
    $(this).attr("data-src",$(this).attr("src"));
    $(this).removeAttr("src");
  }); 
</script>

<img src="test.jpg" width="300" height="200">

I want this output:

<img data-src="test.jpg" width="300" height="200">
rickvdbosch
  • 14,105
  • 2
  • 40
  • 53
Pardeep Kumar
  • 83
  • 1
  • 9
  • 1
    This code should work fine. Are you sure the `data-src` attr is not appearing in the DOM? Inspect the element. – Mitya Aug 28 '17 at 10:51
  • You'd better describe the expected result. Description looks strange for now – Anarion Aug 28 '17 at 10:52
  • 2
    Is the Javcascript code inside `$(document).ready()`? – Barmar Aug 28 '17 at 10:53
  • That code works just fine. In js fiddle anyways...something else is the problem here. Are you infact including Jquery?? And is it inside $(document).ready() ? https://jsfiddle.net/Lfst5evp/ – Kylie Aug 28 '17 at 10:54
  • @KyleK jsFiddle has its own login of placing JS and HTML. Looks like issue is really in "document ready". – Anarion Aug 28 '17 at 10:58
  • @kumar-soni Are you sure that you need what you do? If you're trying to change normal img loading to lazy-loading, this might not work (if this html code is already in DOM) as images will start loading before you change img's src attributes. – Anarion Aug 28 '17 at 10:58

2 Answers2

0

try below code:

$("img").each(function() {
    
        $(this).attr("data-src",$(this).attr("src"));
        $(this).removeAttr("src");
        console.log($(this)[0].outerHTML);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

 
     </script>
        <img src="test.jpg" width="300" height="200">
chirag satapara
  • 1,947
  • 1
  • 15
  • 26
0

You need to execute your JS code after you add image in HTML, like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="test.jpg" width="300" height="200">
<script>

$("img").each(function() {
  var $this = $(this);
  var src = $this.attr("src");
  $this.attr( "data-src", src );
  $this.removeAttr("src");
}); 

</script>
myxobek
  • 445
  • 3
  • 10