查找所有元素具有某些指定属性以外的任何属性 [英] Find all elements have any attribute other than some specified attributes

查看:47
本文介绍了查找所有元素具有某些指定属性以外的任何属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I find all elements have any attribute other than some specified attributes? for example: any other attributes excepts (href + title + id).

推荐答案

做到这一点的唯一方法是循环浏览页面中的所有元素,并过滤掉不需要的元素.

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

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

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.

这篇关于查找所有元素具有某些指定属性以外的任何属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆