RAN
RAN

Reputation: 1453

How to find and replace image inside <div> using jquery?

I am trying to check the image and replace the image for my expand and collapse <div> but i cant able to find the solution.

html code:

<h4 id="expanderHead">Virtual Room <span id="expanderSign">+</span></h4>
<div id="expanderContent" style="display:none">
    content ... content...
</div>

jquery:

$(document).ready(function(){
   $("#expanderHead").click(function(){
      $("#expanderContent").slideToggle();
      if ($("#expanderSign").text() == "+"){
          $("#expanderSign").html("-")
      }
      else {
          $("#expanderSign").text("+")
      }
    });
});

Here, instead of + and - i have to place <img src="" alt=""/> .

Thank you.

Upvotes: 1

Views: 6795

Answers (2)

Ahsan Khurshid
Ahsan Khurshid

Reputation: 9469

HTML

<h4 id="expanderHead">Virtual Room <span id="expanderSign"><img src="plus-sign.png" /></span></h4>
<div id="expanderContent" style="display:none">
    content ... content...
</div>​

EDITED (Added better jQuery Version)

jQuery New Version

$(document).ready(function(){

   $("#expanderHead").click(function(){

       $("#expanderContent").slideToggle();

       var plusImg = "http://cdn2.iconfinder.com/data/icons/diagona/icon/16/129.png";
       var minusImg = "http://cdn2.iconfinder.com/data/icons/diagona/icon/16/130.png";        
       $this = $("#expanderSign img");            

       if( $this.attr('src') == plusImg ) { $this.attr('src', minusImg);} 
       else { $this.attr('src', plusImg); }

   });
});

SEE LIVE DEMO

Upvotes: 7

Mukilarasan
Mukilarasan

Reputation: 747

$(document).ready(function(){

       $("#expanderHead").click(function(){
      $("#expanderContent").slideToggle();
      if ($("#imgId").attr('src') == "d2.png"){
          $("#imgId").attr("src","d1.png")
      }
      else {
          $("#imgId").attr("src","d2.png")
      }
    });
});

    <h4 id="expanderHead">Virtual Room <img id='imgId' src='d2.png' /></h4>
<div id="expanderContent" style="display:none">
    content ... content...
</div>

Upvotes: 0

Related Questions