0

I am getting console.log($(this).attr('src')) as undefined. I want to modify src attribute of all img elements in loop.

$(document).ready(function() {

  $("#btn1").click(() => {

    $(".images").each(() => {
      console.log($(this).attr('src')); // getting undefined
      var srcText = $(this).attr('src');
      var srcArr = srcText.split('?').split('?');
      srcArr[srcArr.length - 1] = genRandQuery();
      $(this).attr('src', srcArr.join('?'));
    });

  });

  function genRandQuery() {
    return 'rnd=' + Math.random().toString(36).substr(7);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<img class="images" src="https://abc?rnd=1234">
<img class="images" src="https://abc?rnd=2354">
<img class="images" src="https://abc?rnd=9876">

<button id="btn1">Show Text</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Mahi
  • 3,748
  • 4
  • 35
  • 70
  • 1
    Just replace `() => {` with `function() {` – palaѕн Apr 08 '20 at 12:06
  • there is not only context problem,split chains are incorrect. when done first split, it Will give you array and array does not have split method. therefore it also will throws error –  Apr 08 '20 at 12:26

1 Answers1

0

 $(document).ready(function(){
    $("#btn1").click(function() {
       $(".images").each( function() { 
         const srcText = $(this).attr('src').split('?');
         const newSrc = `${srcText[0]}?${genRandQuery()}`;
          console.log(newSrc)
         $(this).attr('src', newSrc);
      });

    });

    function genRandQuery() {
      return 'rnd=' + Math.random().toString(36).substr(7);
    }

 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="images" src="https://abc?rnd=1234">
<img class="images" src="https://abc?rnd=2354">
<img class="images" src="https://abc?rnd=9876">

<button id="btn1">Show Text</button>