Search code examples
javascriptjquerysrcprop

changing the img src with jquery


The html structure I have is something like:

<ul id="something">
  <li>
    <a href="">
      <img src="http://domain.com/directory/file1-128x79.jpg">
    </a>
  </li>
  <li>
    <a href="">
      <img src="http://domain.com/directory/file2-128x79.jpg">
    </a>
  </li>
  <li>
    <a href="">
      <img src="http://domain.com/directory/file3-128x79.jpg">
    </a>
  </li>
</ul>

I'm trying to change the filename from file#-128x79.jpg to file#-896x277.jpg.

I don't know how to take the dynamically generated filename and search and replace for the src changes.

I found my way to replacing the whole src with 'none' to make sure I got it right so far, but I don't know how to do the rest.

$('#something').removeAttr('id').prop('class', 'some-class').find('img').prop('src', 'none');

Solution

  • You can replace the src for each img by first selecting all the images with a selector and then using the attr callback to replace the contents:

    $('#something img').attr('src',function(i,e){
        return e.replace("-128x79.jpg","-896x277.jpg");
    })