简体   繁体   English

如何遍历 HTML 元素中的所有属性?

[英]How to iterate through all attributes in an HTML element?

I need the JavaScript code to iterate through the filled attributes in an HTML element.我需要 JavaScript 代码来遍历 HTML 元素中的填充属性。

This Element.attributes ref says I can access it via index, but does not specify whether it is well supported and can be used (cross-browser).这个Element.attributes ref 说我可以通过索引访问它,但没有指定它是否得到很好的支持和可以使用(跨浏览器)。

Or any other ways?还是有其他方式? (without using any frameworks, like jQuery / Prototype) (不使用任何框架,如 jQuery / Prototype)

This would work in IE, Firefox and Chrome (can somebody test the others please? — Thanks, @Bryan):这适用于 IE、Firefox 和 Chrome(有人可以测试其他的吗?-谢谢,@Bryan):

for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    console.log(attrib.name + " = " + attrib.value);
}

EDIT: IE iterates all attributes the DOM object in question supports, no matter whether they have actually been defined in HTML or not.编辑:IE 迭代有问题的 DOM 对象支持的所有属性,无论它们是否实际上已在 HTML 中定义。

You must look at the attrib.specified Boolean property to find out if the attribute actually exists.您必须查看attrib.specified Boolean 属性以确定该属性是否确实存在。 Firefox and Chrome seem to support this property as well: Firefox 和 Chrome 似乎也支持这个属性:

for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    if (attrib.specified) {
        console.log(attrib.name + " = " + attrib.value);
    }
}

Another method is to convert the attribute collection to an array using Array.from :另一种方法是使用Array.from将属性集合转换为数组:

Array.from(element.attributes).forEach(attr => {
  console.log(`${attr.nodeName}=${attr.nodeValue}`);
})

In case anyone is interested in a filtered version, or is trying to build CSS attribute selectors, here you go:如果有人对过滤版本感兴趣,或者正在尝试构建 CSS 属性选择器,请访问:

let el = document.body;
Array.from(el.attributes)
    .filter(a => { return a.specified && a.nodeName !== 'class'; })
    .map(a => { return '[' + a.nodeName + '=' + a.textContent + ']'; })
    .join('');

//outputs: "[name=value][name=value]

You can certainly remove the join to retreive an array or add a filter for "style" since in most web applications the style tag is widely manipulated by widgets.您当然可以删除连接以检索数组或为“样式”添加过滤器,因为在大多数 Web 应用程序中,样式标记被小部件广泛操纵。

更高效

Array.prototype.forEach.call(elm.attributes, attr => console.log(attr))

The most simple approach is to use spread operator.最简单的方法是使用扩展运算符。

 const el = document.querySelector('div'); [...el.attributes].forEach((attr) => { console.log(attr.name + ' = ' + attr.value); });
 <div class="foo" id="bar"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM