kumar soni kumar soni - 1 month ago 10
HTML Question

How to change img src attribute to data-src in javascript?

I am using this code to change image src attribute to data-src attribute but it does not work I don't know where I am doing wrong any help would be appreciated.Thanks

<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">

Answer Source

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">