简体   繁体   中英

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.

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/

something like

$("div:has(img)")

if you are using jquery

You can get the image elemant by using js getElementById then you can easily access the src of that image, which tells you weather element contains image if src is not empty or if contains then src should have image path.

   <html>
    <head>
    <script>
    function myFunction()
    {
     var imgSrc = document.getElementById("myImg").attr('src');
     alert(imgSrc);
    }
    </script>
    </head>

    <body>

    <h1>My Web Page</h1>

    <p id="demo">A Paragraph</p>

    <img id="myImg" src="http://www.blah.com/img.jpg" onclick="myFunction()"></img>

    </body>

</html>

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