简体   繁体   中英

Check if contents of a DIV is only an Image

I have a div containing initially a loader image tag.

  <img src="/images/indicator_big.gif" style="display:block;margin:auto">

I want to check if the DIV contains only the loader image then the function should trigger an Ajax Request.

If i do some thing like div.innerHTML I get it as a string.

What will be the best way to test if the innerHTML is only a loader image?

You can check how many elements are inside your element

var children = document.querySelector("#yourDiv > *");
if (children.length == 1 && children[0].tagName.toLowerCase() == "img") {
    //you only have one child in here, and that's an image
}

This will be 1 if it only contains your initial image.

Be wary of the browser support, though: http://www.quirksmode.org/dom/w3c_core.html#t13

This method will do what you ask, although I'm not sure the general approach is the best to be honest.

function hasOnlyImg(div) {
  if (div.children.length != 1)
    return false;
  return div.children[0].tagName == "IMG";
}

I'm assuming your 'style.display' of that loader image will change? You could just check for that?

function checkDiv(div,func) {
    var thisDiv = div;
    var imgLink = thisDiv.getElementsByTagName("img");
    if (imgLink.length == 1 && imgLink[0].style.display !== "block") {
        func();
    }
}
checkDiv(document.getElementById("mydiv"),function() {
    //call ajax code
});

Or if you still would like to check the number of HTML tags within your div, just do something like:

var allDivTags = mydiv.getElementsByTagName("*");
if (allDivTags.length == 1 && allDivTags.nodeName.toLowerCase() == "img") {
    //only 1 html element exists in the div, and it's an image.
    //run code
}

Hope this helps.

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