简体   繁体   中英

How can count all images on a page with JavaScript (including CSS and img)

It's trivial to get the <img> elements on a page with JavaScript:

  • document.images
  • document.getElementsByTagName('img')

But is there a (reasonably easy) way to get all images loaded on the page?

I've considered looping through all elements using querySelectorAll('*') and checking their style.background and style.backgroundImage properties for url , then combining that with the html image elements.

Is that approach my only choice? Will that catch everything? I imagine there are edge cases with images loaded by JavaScript, new HTML5 image elements (picture, ...).

I'm not yet sure how I want to handle data-uri images or SVG, but if an answer covered that, it'd probably be a good thing.

Made a new answer, this one will find all elements with a certian background, and can definitely be modified for all items that have a background or a couple different backgrounds.

Also you could modify for length of string, make sure it isn't an empty string and therefore has a background and then count that element.

* JavaScript Solution *

I would say going though all elements is your only choice by what you have stated.

 var count = 0; window.onload = function () { var elems = document.body.getElementsByTagName("*"); for(var i = 0; i < elems.length; i++) { var properties = (elems[i].currentStyle || window.getComputedStyle(elems[i], false)); background = properties.backgroundImage.slice(4, -1); if(background.indexOf("http://placehold.it/50x50") > -1) { count++; } } alert(count); };
 p { background: url('http://placehold.it/50x50'); }
 <div class="main"> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> </div>

Yes, I think you have to search through all elements and for each one obtain its image, depending on the type of element.

Here's a functional code that will give you all images in a webpage inside IMG tags and also other common places (DIVs, Ps, etc). You can expand the search to other tags, or even to all tags. It won't search in SVG and other " non-basic " forms of placing images:

var imageSearch = 
{
    image_array: {},
    valid_image_nodes: ["DIV", "P", "SECTION", "SPAN"],

    scan_for_valid_images: function(node) 
    {
        if (node.nodeType === 1) 
        {
            if (node.nodeName === "IMG") {
                this.image_array[node.getAttribute("src")] = true;
            }
            else
            {
                if (this.valid_image_nodes.indexOf(node.nodeName) !== -1) {
                    div_style = node.currentStyle || window.getComputedStyle(node, false);
                    if (div_style.backgroundImage !== "none") {
                        url = div_style.backgroundImage;
                        this.image_array[url.slice(4, url.indexOf(')'))] = true;
                    }
                }
            }
        }
        var children = node.childNodes;
        for (var i = 0; i < children.length; i++) {
            this.scan_for_valid_images(children[i]);
        }
    },

    get_image_array: function()
    {
        return Object.keys(this.image_array)
    }
}

imageSearch.scan_for_valid_images(document);
imageSearch.get_image_array()

Try copy-pasting that into the console of this window to see it in action.

You can count with CSS using the counter-reset and counter-increment and count items with CSS.

 body { counter-reset: img; } img { counter-increment: img; content:counter(img); content:""; } div.main:after { content: "Images Counted: " counter(img); }
 <div class="main"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> </div>

However to count all the items you want you could do:

 body { counter-reset: count; } img { counter-increment: count; content:counter(count); content:""; } p:before { counter-increment: count; content:counter(count); content:""; } h1:before { counter-increment: count; content:counter(count); content:""; } div.main:after { content: "Items Counted: " counter(count); }
 <div class="main"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <p> This paragraph is also counted </p> <h1> This header 1 is also counted </h1> </div>

You could also place this information in a hidden div and extract it later, if needed.

Here is something for reference: http://www.webdesignerdepot.com/2013/05/learn-to-count-with-css/

You can do the following at the bottom of the page:

<script type="text/javascript">
    var imgCount = document.images.length;
    var svgCount = document.getElementsByTagName('svg').length;
    var finalCount = imgCount + svgCount;
</script>

with jquery you can use something like this for counter backgroundImage

var ctBkImg = 0;
$("*").each(function(){
    if ($(this).css("background-image") != "none" ) ctBkImg++
}); 

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