How to check how many elements of a certain type h

2019-01-15 20:48发布

问题:

I have a simple custom Chrome Extension I've looked all over the web for this and nothing good showed up. I want to read how many elements of a certain type are in a page, through my popup.js file.

Something like this:

$('div').length

Is it possible to do this through the chrome.tabs command?

回答1:

  1. manifest.json:

    "permissions": [
        "tabs",
        "activeTab"
    ]
    
  2. Code:

    function countTags(tag, callback) {
        chrome.tabs.executeScript({
            code: "document.getElementsByTagName('" + tag + "').length"
        }, function(result) {
            if (chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError);
            } else {
                callback(result[0]);
            }
        });
    }
    
  3. Usage:

    countTags("div", function(num) {
        console.log("Found %i divs", num);
    });
    

    getElementsByTagName(tag) can be replaced with querySelectorAll(selector) or jQuery syntax if you are sure the tab has jQuery loaded.