user3484851
user3484851

Reputation: 33

jQuery find('img').attr('src') does not work

The following code will not work:

find('img').attr('src')

I want hover on aside area and image change on/off.

HTML

<aside style="width:200px;height:300px;text-align:center;">
  <img class="img" src="imgs/photo_off.png" alt="" >
</aside>

JavaScript

$("aside").hover(
    function () {
        $(this).find('img').attr('src') = $(this).find('img').attr('src').replace("_off", "_on");
    },
    function () {
        $(this).find('img').attr('src') = $(this).find('img').attr('src').replace("_on", "_off");
    }
);

Upvotes: 0

Views: 22272

Answers (2)

Murali Murugesan
Murali Murugesan

Reputation: 22619

$(this).find('img')[0].src = $(this).find('img').attr('src').replace("_off", "_on");

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can't assign a value to a function call statement like that. It should thrown an error like

Uncaught ReferenceError: Invalid left-hand side in assignment

Use the setter version of .attr(name, value)

$(this).find('img').attr('src', $(this).find('img').attr('src').replace("_off", "_on"));

or .attr(name, callback)

$("aside").hover(function () {
    $(this).find('img').attr('src', function (i, src) {
        return src.replace("_off", "_on");
    })
}, function () {
    $(this).find('img').attr('src', function (i, src) {
        return src.replace("_on", "_off");
    })
});

Upvotes: 5

Related Questions