Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How can I check if an element contains an image?

Can anyone suggest how I could check if an element contains an image? I'm assuming it would be whether or not it contains the image source but am unsure how to code this.

like image 780
jord49 Avatar asked Mar 23 '13 20:03

jord49


3 Answers

You can do this like so:

if( elem.getElementsByTagName('img').length > 0) {
    // there is an image
}

EDIT: After seeing your comment, try this:

var imgs = elem.getElementsByTagName('img'), len = imgs.length, i;
for( i=0; i<len; i++) {
    if( imgs[i].src.match(/\/image\.jpg$/)) {
        // the image is there
        break;
    }
}
like image 163
Niet the Dark Absol Avatar answered Sep 28 '22 09:09

Niet the Dark Absol


If you are using jQuery you can do something like that :

if($('#container_id').find('img').length > 0) {
     // Image found on container with id "container_id"
}
like image 41
Ifnot Avatar answered Sep 28 '22 10:09

Ifnot


This should work and won't require JQuery like Anael's solution:

<div id="test1"><img src="img.jpg" /></div>
<div id="test2">Hello</div>    

<script>
function hasImage(id) {
    var childElements = document.getElementById(id).childNodes;
    for (var i = 0; i < childElements.length; i++) {
        if (childElements[i].localName != null && childElements[i].localName.toLowerCase() == "img") {
            return true;
        }
    }
    return false;
}

alert(hasImage('test1')); // true
alert(hasImage('test2')); // false
</script>

Demo at JSFiddle: http://jsfiddle.net/qLPJC/

Update:

To see if it has a specific src try this update:

function hasImage(id) {
    var childElements = document.getElementById(id).childNodes;
    for (var i = 0; i < childElements.length; i++) {
        if (childElements[i].localName != null && childElements[i].localName.toLowerCase() == "img") {
            if (childElements[i].getAttribute('src') != null && childElements[i].getAttribute('src').toLowerCase() == "img.jpg") {
                return true;
            }
        }
    }
    return false;
}

alert(hasImage('test1'));
alert(hasImage('test2'));

Updated JS Fiddle example: http://jsfiddle.net/qLPJC/2/

like image 33
Adam Plocher Avatar answered Sep 28 '22 11:09

Adam Plocher