Steffan Harris
Steffan Harris

Reputation: 9326

How to check if an element contains an image?

How do I check to see if an element contains an image. Can't I do something like this

if(document.getElementById("image").src == myImage.src)

Upvotes: 1

Views: 1822

Answers (2)

Phil
Phil

Reputation: 164813

function hasImage(element, src) {
    var images = element.getElementsByTagName("img");
    for (var i = 0; i < images.length; i++) {
        if (images[i].getAttribute("src") == src) {
            return true;
        }
    }
    return false;
}

console.log(hasImage(document.getElementById("image"), myImage.src));

If your browser supports it, you can use element.querySelector()

var img = document.getElementById("image")
                  .querySelector("img[src='" + myImage.src + "']");
console.log(img ? "Found" : "Not found");

Upvotes: 4

JaredPar
JaredPar

Reputation: 754763

Are you trying to check if an img tag with the id "image" has a src attribute equal to a different img tag? If so try the following

if (document.getElementById('image').getAttribute('src') === myImage.getAttribute('src)) {
  ...
}

If you just want to see if it has an src attribute at all then you can do the following

if (document.getElementById('image').getAttribute('src')) {
  ...
}

Upvotes: 2

Related Questions