JQuery replace src attribute substring

1.8k views Asked by At

I'd like to replace the 2's with 1's for the image src in all matching classes. I've tried something similar for specific elements and thats works, but I can't get it to work for all matching classes. How do I change the format of the first call so it works? Thanks.

$(".in1, .in2, .in3").click(
    function()
    {    
        $(".in1, .in2, .in3").attr("src").replace("2","1");// This doesn't work

        if(this.src.indexOf("1")!=-1){
            this.src = this.src.replace("1","2"); // This works
        }else{
            this.src = this.src.replace("2","1"); // This works
        }
    }
);
2

There are 2 answers

0
alex On
$(".in1, .in2, .in3").attr('href', function(index, attr) {
   return attr.replace('1', '2');
});
0
Reigel Gallarde On

.attr("src") is a getter and not a setter.

if you want it as a setter, you can do this,

.attr("src", function(i,src){
   return (src.indexOf("1")!=-1)?src.replace("1","2"):src.replace("2","1");
});

requires jQuery 1.4 + , .attr() link