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.
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;
}
}
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"
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With