简体   繁体   中英

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)
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");

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')) {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM