查找所有元素除了某些指定属性之外还有任何属性

时间:2013-01-08 23:32:21

标签: javascript attributes

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

执行此操作的唯一方法是遍历页面中的所有元素并过滤掉您不想要的元素。

在此实现中,您传递要忽略的属性数组(以及可选的标记类型),并返回一个元素数组,这些元素的某些属性不是您传入的属性之一:

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");

这使用.attributes集合来获取HTML中为给定元素指定的所有属性的列表,然后查看属性节点上的.name属性以查看给定元素的名称属性是。