Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 601
gavsiu Avatar asked Jul 04 '11 07:07

gavsiu


People also ask

Can you change img src?

Change Img src If you'd like to replace an image on your website, then you can simply change the image file path or URL in its source attribute. You can change this attribute at any time.

Can we change image src using JavaScript?

JavaScript provides a src attribute to change the image source by specifying the path of the file. For instance, the getElementId() method is utilized to extract the HTML element through id, and then the src property will change the source image. After extraction, the new source image file is assigned.

Can we change in jQuery?

jQuery change() MethodThe change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs.


2 Answers

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");
})
like image 167
Niklas Avatar answered Oct 05 '22 08:10

Niklas


you can assign an id to your image tag like

<img id ="pic" src="http://domain.com/directory/file3-128x79.jpg">

then in jquery use

$('#pic').attr('src', 'file#-896x277.jpg');
like image 36
Muhammad Adeel Zahid Avatar answered Oct 05 '22 08:10

Muhammad Adeel Zahid