Iterating over element attributes with jQuery

早过忘川 提交于 2019-12-17 07:25:51

问题


I know individual attributes can be retrieved with the attr() method, but I'm trying to iterate over all of the attributes for an element. For context, I'm using jQuery on some 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>

I am already able to iterate over the items with...

$(xml).find('item').each(function() {
  // Do something to each item here...
});

But I'd like to be able to get an array of attributes for each 'item' so I can then iterate over those...

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

I've done some searching here, in the jQuery documentation, and elsewhere via Google but have had no luck. If nothing else, I may just be having trouble excluding results relating to the attr() method of the jQuery object. Thanks in advance.


回答1:


The best way is to use the node object directly by using its attributes property. The only difference in my solution below compared to others suggesting this method is that i would use .each again instead of a traditional js loop:

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



回答2:


it seems you have to use plain old vanilla 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?




回答3:


Could you get the DOM element from the jQuery wrapper using the get() function, and then iterate the DOM attributes?

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

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

        }
    }
}

For some much more robust DOM attribute handling, check this blog post.




回答4:


How about?

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



回答5:


While you can just use the standard DOM Element attribute attributes, it will include every attribute (even those not explicitly set) in IE6. As an alternative, you can limit the number of attributes you set:

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



回答6:


I am posting here because I think it may help others that arrive at this posting looking to parse an xml file as I was.

I was looking for a method of traversing an xml file with a very similar structure to theracoonbear's fle and storing the results in an array and came across this posting.

I looked at prodigitalson's code but I simply could not get this syntax to work - with firefox complaining that in the line:

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

that

this.attributes

is not a defined function. I am quite sure that the error is entirely mine. But I have spent several hours attempting to get this working and have failed

What worked for me was (where my tag name is session instead of item):-

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

I appreciate that this may not exactly answer the original question. However I hope that it may save other visitors to this post some time.

Regards




回答7:


created this generic function that allows to look-in attributes as well as innearHtml:

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



回答8:


Pure JS First, your input xml is not valid, but you can fix it by close subitem tags by /

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


来源:https://stackoverflow.com/questions/2224933/iterating-over-element-attributes-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!