使用jQuery迭代元素属性

时间:2010-02-08 21:17:45

标签: jquery xml dom traversal

我知道可以使用attr()方法检索单个属性,但我正在尝试迭代元素的所有属性。对于上下文,我在一些XML上使用jQuery ...

<items>
  <item id="id123" name="Fizz" value="Buzz" type="xyz">
    <subitem name="foo">
    <subitem name="bar">
  </item>
  <item id="id456" name="Bizz" value="Bazz" type="abc">
    <subitem name="meh">
    <subitem name="hem">
  </item>
</items>

我已经可以使用...

迭代这些项目了
$(xml).find('item').each(function() {
  // Do something to each item here...
});

但我希望能够为每个“项目”获取一系列属性,以便我可以迭代这些...

e.g。

$(xml).find('item').each(function() {
  var attributes = $(this).attributes(); // returns an array of attributes?
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});

我已经在jQuery文档中进行了一些搜索,并在谷歌的其他地方进行了搜索,但没有运气。如果不出意外,我可能只是在排除与jQuery对象的attr()方法相关的结果时遇到问题。提前谢谢。

8 个答案:

答案 0 :(得分:103)

最好的方法是使用其attributes属性直接使用节点对象。与其他人相比,我的解决方案中唯一的区别是建议使用此方法,我将再次使用.each而不是传统的js循环:

$(xml).find('item').each(function() {
  $.each(this.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
     // do your magic :-)
  });
});

答案 1 :(得分:10)

似乎你必须使用普通的旧香草javascript:

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

How to iterate through all attributes in an HTML element?

答案 2 :(得分:4)

你能使用get()函数从jQuery包装器中获取DOM元素,然后迭代DOM属性吗?

var node = $(myStuff).get(0);
if (node.attributes.length) {

    for (var length = attrs.length, i = 0; i < length; i++) {
        if (attrs[i].specified) {

        }
    }
}

对于一些更强大的DOM属性处理,check this blog post

答案 3 :(得分:1)

怎么样?

$(xml).find('item').each(function() {
  var attributes = $(this)[0].attributes;
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});

答案 4 :(得分:1)

虽然您可以使用标准DOM元素属性attributes,但它将在IE6中包含每个属性(甚至那些未明确设置的属性)。作为替代方案,您可以限制您设置的属性数量:

var use_attributes = ['id','name','value','type'];
$(xml).find('item').each(function() {
  var $item = $(this);

  $.each( use_attributes, function(){
    if($item.attr( this )){
      // Act on the attribute here. 
      // `this` = attribute name
      // $item.attr( this ) = attribute value
    }
  })
});

答案 5 :(得分:1)

我在这里发帖是因为我认为这可能有助于其他人到达此帖子,希望像我一样解析xml文件。

我一直在寻找一种遍历xml文件的方法,该文件具有与theracoonbear的文件非常相似的结构,并将结果存储在一个数组中,并且发现了这个帖子。

我查看了prodigitalson的代码,但我根本无法使用这种语法 - 使用firefox在行中抱怨:

 $.each(this.attributes, function(i, attrib){

  

this.attributes

不是已定义的函数。 我很确定错误完全是我的。但是我花了几个小时试图让这个工作失败

对我有用的是(我的标签名称是会话而不是项目): -

$(xml_Data).find("session").each(function() {
    console.log("found session");
    $(this).children().each(function(){
     console.log("found child " + this.tagName);
     console.log("attributes" + $(this).text());
    });
});

我很欣赏这可能不能完全回答原来的问题。但是我希望它可以在一段时间内保存其他访问者。

此致

答案 6 :(得分:1)

function findByAll(toLookFor, lookInText) { 
    return $('*').filter(function() { 
        return Array.prototype.some.call(this.attributes, function(attr) {
            return attr.value.indexOf(toLookFor) >= 0; 
        }) || (lookInText && $(this).text().indexOf(toLookFor) >= 0); 
    }); 
}

答案 7 :(得分:-1)

纯JS 首先,您输入的xml不是valid,但是您可以通过/

关闭子项标签来修复它
let items = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));

let xml=`<items>
  <item id="id123" name="Fizz" value="Buzz" type="xyz">
    <subitem name="foo" />
    <subitem name="bar" />
  </item>
  <item id="id456" name="Bizz" value="Bazz" type="abc">
    <subitem name="meh" />
    <subitem name="hem" />
  </item>
</items>`;

let items  = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));

相关问题