Search code examples
jquerytextreplacesrc

JQuery replace src text


How to replace the src text "web" to "mobile" for all ul>li>ing element? Would like to change "img/web1.png" to "img/mobile1.png", "img/web2.png" to "img/mobile2.png", "img/web7.png" to "img/mobile7.png" and so on.

<div class="col-md-2">  
      <center><a href="#"><div class="img-circle" id="circle2">Mobile</div></a></center>
      <br/> 
</div>

<div id = "wrapper">
        <ul id = "portfolio">
            <li><img class="img-thumbnail" src="img/web1.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web2.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web3.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web4.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web5.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web6.png" alt = "img"/></li> 
            <li><img class="img-thumbnail" src="img/web7.png" alt = "img"/></li> 

            <button id="zoom" type="button" class="btn btn-info"> 
                <span class="glyphicon glyphicon-search"> Zoom </span> 
            </button>
        </ul> 

    </div>

    $("#circle2").click(function(){ 
      $("#portfolio>li").first().children("img").attr("src","img/mobile1.png");
    });

Solution

  • You could loop through the li elements, find the img element and do a replace on the src property.

    $(document).ready(function () {
        $("#circle2").click(function () {
    
            // Loop through all li elements in the 
            //     element with the id of portfolio
            $("#portfolio").find("li").each(function () {
       
                // Find the image tag
                var img = $(this).find("img");
          
                // Update the src property to the same thing, 
                //       replacing web with mobile
                img.prop("src", img.prop("src").replace("web", "mobile"));
    
            }); // end li loop
        }); // end change stuff click event
    }); // end doc ready
    

    You can see a working JSFiddle here

    References: