1

我怎样才能找到所有元素都具有除某些指定属性之外的任何属性?例如:除 (href + title + id) 之外的任何其他属性。

4

2 回答 2

2
var attrs = ["href", "title", "id"],
    els = document.getElementsByTagName("*"),
    result = Array.prototype.slice.call(els).filter(function(el) {
        if (el.attributes.length === 0)
            return false;

        for (var i = 0, l = attrs.length; i < l; i++) {
            if (el.hasAttribute(attrs[i]))
                return false;
        }
        return true;
    });

console.log(result);
于 2013-01-08T23:41:25.477 回答
1

The only way to do this is to loop through ALL elements in the page and filter out the ones you don't want.

In this implementation, you pass an array of the attributes that you want to ignore (and optionally a tag type) and it returns an array of elements that have some attribute other than one of those you passed in:

function getElemsWithOtherAttribute(attArray, tags) {
    tags = tags || "*";
    // put all passed in attributes in an object for fast lookup
    // add leading underscore to avoid any built-in property conflicts
    var attLookup = {}, i, j, len, results = [], atts;
    for (i = 0, len = attArray.length; i < len; i++) {
        attLookup["_" + attArray[i].toLowerCase()] = true;
    }
    // get all elements and loop through them all
    var elems = document.getElementsByTagName(tags);
    for (i = 0, len = elems.length; i < len; i++) {
        // get all attributes on this element and loop through them all
        // until we find one that isn't in our attLookup object
        atts = elems[i].attributes;
        for (j = 0; j < atts.length; j++) {
            // if we have an attribute name that is not in our passed in list, then
            // add this element to the results array
            if (attLookup["_" + atts[j].name.toLowerCase()] !== true) {
                results.push(elems[i]);
                break;
            }
        }
    }
    return(results);
}

// example usage
var regAttributes = ["href", "title", "id"];
var items = getElemsWithOtherAttribute(regAttributes, "img");

This uses the .attributes collection to get a list of all attributes specified in the HTML for a given element and then looks at the .name property on the attribute node to see what the name of that given attribute is.

于 2013-01-08T23:39:02.310 回答