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

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

问题描述

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



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



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

这可以在IE,Firefox和Chrome中工作(可以有人测试($ i = 0; i< elem.attributes.length ; i ++){
var attrib = elem.attributes [i];
console.log(attrib.name +=+ attrib.value);

$ / code>

编辑:IE遍历所有属性的DOM对象有问题的支持,不管它们是否实际上是用HTML定义的。

您必须查看 attrib.specified 布尔属性以确定该属性是否实际存在。 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);
}
}


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

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

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

解决方案

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

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

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天全站免登陆