I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:
<span name="test" message="test2"></span>
now one way is to use the xml parser described here, but then i need to know how to get the html code of my object.
the other way is to make it with jquery, but how? the number of attributes and the names are generic.
Thanks
Btw: I can't access the element with document.getelementbyid or something similar.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.
To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.
If you just want the DOM attributes, it's probably simpler to use the attributes
node list on the element itself:
var el = document.getElementById("someId"); for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){ arr.push(atts[i].nodeName); }
Note that this fills the array only with attribute names. If you need the attribute value, you can use the nodeValue
property:
var nodes=[], values=[]; for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){ att = atts[i]; nodes.push(att.nodeName); values.push(att.nodeValue); }
You can use this simple plugin as $('#some_id').getAttributes();
(function($) { $.fn.getAttributes = function() { var attributes = {}; if( this.length ) { $.each( this[0].attributes, function( index, attr ) { attributes[ attr.name ] = attr.value; } ); } return attributes; }; })(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With