首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JavaScript/jQuery:如何获取XML元素中所有属性的数组?

JavaScript/jQuery:如何获取XML元素中所有属性的数组?
EN

Stack Overflow用户
提问于 2009-11-10 11:42:36
回答 3查看 11.1K关注 0票数 1

在jQuery中给定一个XML元素,如下所示:

代码语言:javascript
运行
复制
$('<foo oy="vey" foo="bar" here="is" another="attribute" />')

是否可以使用jQuery或普通旧式JavaScript来获取包含XML元素中所有属性名称的数组?我希望是这样的:

代码语言:javascript
运行
复制
['oy','foo','here','another']
EN

Stack Overflow用户

发布于 2018-03-29 02:55:36

A)单个<Foo>元素

您是否需要单个元素的属性列表?

..。如果需要,您真的需要阵列吗?

简单的$('<foo ... />').get(0).attributes

...will 提供NamedNodeMap (object) of attributes

B)整个(XML)文档中的所有元素<Foo>

@Soufiane Hassou的答案是显示方法,但缺少内部循环...

您是否需要获取整个文档中某个元素(例如,Product元素)的所有可能的属性名称

代码语言:javascript
运行
复制
var yourElements = document.getElementsByTagName('Foo'); //get all <Foo> elements
var listOfAttributeNames = []; //prepare empty array for attribute names
var attributeNameBuffer; //buffer for current attribute name in loop

//Loop all elements
for(var i = 0; i < yourElements.length ; ++i){ 

   //Loop all attributes of a current element
   for( k = 0 ; k < yourElements[i].attributes.length ; ++k ){ 
       //Temporary store current attribute name
       attributeNameBuffer = yourElements[i].attributes[k].name;

       //First, 
       //test if the attribute name does not already exist in our array of names
       if( listOfAttributeNames.indexOf(attributeNameBuffer) == -1 )
         listOfAttributeNames.push( attributeNameBuffer ); //if not, add it
   }

} 
console.log(listOfAttributeNames); //display array of attributes in console
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1705504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档