Pregunta

I'm looking to change the source attribute of an image element when my parent element is clicked. The child/image element is actually nested within two div's which complicates things slightly and I have a suspicion this is where i'm going wrong in my code.

The JavaScript is as follows:

    <script src="js/jquery-1.7.2.min.js"></script>
  <script>
      $(document).ready(function () {
          $('.slideContent').hide();
          $('.slideHeader').toggle(
                 function () {
                     $(this).next('.slideContent').slideDown();
                     $(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";
                 },
                 function () {
                     $(this).next('.slideContent').fadeOut();
                     $(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconDown.png";
                 }
             ); // end toggle
      }); // end ready

And the HTML is:

<div class="slideHeader">
  <div class="dropDownIcon">
   <img class="dropDownClass" src="./images/dropDownIconDown.png"/>
  </div>
  <div>
   <p>2014</p>
  </div>
</div>
<div class="slideContent">
  <div>
    <p>2014</p>
  </div>
</div>

The slideDown and fadeOut functions from jQuery work fine. However the image change does not happen. So i'm confident my eror is within the following code:

$(this).children('.dropDownIcon').children('img').src = "./images/dropDownIconUp.png";

But as far as I can see, I select the correct elements in my chain. If anyone can shine any light on this it would be much appreciated. As everything else on the internet verifys the code above should work (Whilst a be little messy).

Thanks in advance.

¿Fue útil?

Solución

src is an attribute of the img tag, so use .attr()

Try,

$(this).children('.dropDownIcon').children('img').attr('src', "./images/dropDownIconUp.png");

Otros consejos

instead of using children selector twice use $(this).find('img').attr('src','./images/dropDownIconUp.png')

I know you have accepted the answer but let me tell you some points in brief

.src = "blah" would not work for jquery objects.$() always returns a jquery object and you must use .attr() or .prop() to work with jquery objects

However jquery provides a simple way to convert to javascript object

if you still want to use as a javascript object you could it this way

$(".slideHeader").children('.dropDownIcon').children('img')[0].src = "./images/dropDownIconDown.png"; 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top