[英]Find all elements have any attribute other than some specified attributes
如何找到除了某些指定屬性之外的所有元素都有任何屬性? 例如:除了(href + title + id)之外的任何其他屬性。
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);
執行此操作的唯一方法是遍歷頁面中的所有元素並過濾掉您不想要的元素。
在此實現中,您傳遞要忽略的屬性數組(以及可選的標記類型),並返回一個元素數組,這些元素的某些屬性不是您傳入的屬性之一:
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
屬性以查看該給定屬性的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.