Skip to content Skip to sidebar Skip to footer

How To Change Img Src Directory Or Image File Name With Jquery Or Php

I would like to change the image path directory or append the the image file by adding a class to the parent container. Example: If I add a class of 'large' to the parent img conta

Solution 1:

For example like this, using lastIndexOf

$function() {
  var img = $(".large-image > img").each(function() { // for each img foundvar src = $(this).attr("src"); // get the srcvar path = src.substring(0,src.lastIndexOf('/')); // get the path from the src var fileName = src.substring(src.lastIndexOf('/')); // and filenamevar newSrc = path+"/large"+fileName; // re-assemble   // or change filename:// var newSrc = path+"/"+fileName.replace(".jpg","-large.jpg"); // re-assemble   

    $(this).attr("src",newSrc);
  });
});

Solution 2:

you can use jquery to change the src, split it, and add your new folder

<div class="large-image">
     <imgsrc="/images/services/image.jpg"alt="" />
</div>

$('.large-image > img').each(function(){
     var msrc=$(this).attr('src');
     msrc=msrc.split('/');     //images, services, image.jpgvar lastelem = msrc.pop();  //images, services     // lastelem: image.jpg
     msrc.push('large');     //images, services, large   // lastelem: image.jpg 
     msrc.push(lastelem);    //images, services, large, image.jpg
     msrc=msrc.join('/');  //"images/services/large/image.jpg"
     $(this).attr('src', msrc);
})

Post a Comment for "How To Change Img Src Directory Or Image File Name With Jquery Or Php"