holyredbeard
holyredbeard

Reputation: 21278

Changing image src with jQuery

I'm replacing some code in an old application, and instead of getting the node by it's id I get it by it's class. Because there isn't a good way to get a node by it's class in native JS I do it with jQuery, however the new code doesn't change the img src.

Is there an obvious reason?

Old code:

var gamearea = document.getElementById('gamearea')
var images = gamearea.getElementsByTagName('img');
images[place] = "pics/" + id + ".png";

New code:

$('.gamearea').children('img').eq(place).src = "pics/" + id + ".png";

Upvotes: 0

Views: 6187

Answers (4)

Matthew Kirk
Matthew Kirk

Reputation: 19

I know this is an old answer, but surely this is a better way...

$('.gamearea').children('img').attr("src", "pics/" + id + ".png");

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108520

Try:

$('.gamearea').children('img').eq(place)[0].src = "pics/" + id + ".png";

or:

$('.gamearea').children('img').eq(place).attr("src", "pics/" + id + ".png");

$('.gamearea').children('img').eq(place) returns a jQuery "array" of elements, you can’t access DOM attributes directly on this object. You need to either pull the DOM element by using [0] (the first element) or use a method from the jQuery api, in this case .attr().

Also, you might mean to use $('#gamearea') instead of $('.gamearea') if you are replacing getElementById('gamearea');

Upvotes: 2

Raynos
Raynos

Reputation: 169511

function updateGameAreaImages(id, place) {
    var gameareas = toArray(document.getElementsByClassName('gamearea'));
    gameareas.forEach(updateImages);

    function updateImages(elem) {
        var images = elem.getElementsByTagName("img");
        images[place].src = "pics/" + id + ".png";
    }
}

function toArray(obj) {
    var arr = [];
    for (var i = 0, len = obj.length; i < len; i++) {
        arr[i] = obj[i];
    }
    return arr;
}

Upvotes: 3

jfriend00
jfriend00

Reputation: 707996

.eq() returns a jQuery object. If you want to use the .src property directly, you need a DOM element (not a jQuery object) for which you would use .get() instead of .eq() like this:

$('.gamearea').find('img').get(place).src = "pics/" + id + ".png";

I also switched to .find() instead of .children() to be more equivalent to .getElementsByTagName() that you had in the original version and since you didn't show us your HTML, it seems a safer assumption.

Upvotes: 1

Related Questions