Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all Attributes from a HTML element with Javascript/jQuery

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.

like image 962
k0ni Avatar asked Jan 12 '10 12:01

k0ni


People also ask

How get data attribute in jQuery?

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

How do I get attributes in HTML?

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.

How do I get HTML using jQuery?

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.


2 Answers

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); } 
like image 193
Roland Bouman Avatar answered Sep 23 '22 01:09

Roland Bouman


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); 
like image 26
manRo Avatar answered Sep 22 '22 01:09

manRo