如何遍历 HTML 元素中的所有属性? [英] How to iterate through all attributes in an HTML element?

查看:26
本文介绍了如何遍历 HTML 元素中的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 JavaScript 代码来遍历 HTML 元素中的填充属性.

I need the JavaScript code to iterate through the filled attributes in an HTML element.

这个 Element.attributes ref 说我可以通过索引访问它,但没有指定它是否得到很好的支持和可以使用(跨浏览器).

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).

或者其他方式?(不使用任何框架,如 jQuery/Prototype)

Or any other ways? (without using any frameworks, like jQuery / Prototype)

推荐答案

这适用于 IE、Firefox 和 Chrome(有人可以测试其他的吗?— 谢谢,@Bryan):

This would work in IE, Firefox and Chrome (can somebody test the others please? — Thanks, @Bryan):

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

IE 迭代 所有 有问题的 DOM 对象支持的属性,无论它们是否实际上已经在 HTML 中定义.

IE iterates all attributes the DOM object in question supports, no matter whether they have actually been defined in HTML or not.

您必须查看 attrib.specified 布尔属性,以确定该属性是否确实存在.Firefox 和 Chrome 似乎也支持此属性:

You must look at the attrib.specified Boolean property to find out if the attribute actually exists. Firefox and Chrome seem to support this property as well:

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

这篇关于如何遍历 HTML 元素中的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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