使用Javascript / jQuery从HTML元素获取所有属性

我想把一个Html元素的所有属性放到一个数组中:就像我有一个jQuery对象,这就像这样:

<span name="test" message="test2"></span> 

现在有一种方法是使用这里描述的XMLparsing器,但是我需要知道如何获取我的对象的HTML代码。

另一种方式是使它与jQuery,但如何? 属性的数量和名称是通用的。

谢谢

顺便说一句:我不能访问与document.getelementbyid或类似的元素。

如果您只是想要DOM属性,那么在元素本身上使用attributes节点列表可能会更简单:

 var el = document.getElementById("someId"); for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){ arr.push(atts[i].nodeName); } 

请注意,这只填充属性名称的数组。 如果您需要属性值,则可以使用nodeValue属性:

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

你可以使用这个简单的插件$('#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); 

简单:

 var element = $("span[name='test']"); $(element[0].attributes).each(function() { console.log(this.nodeName+':'+this.nodeValue);}); 

因为在IE7中,elem.attributes列出了所有可能的属性,而不仅仅是现在的属性,我们必须testing属性值。 这个插件适用于所有主stream浏览器:

 (function($) { $.fn.getAttributes = function () { var elem = this, attr = {}; if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { n = n.nodeName||n.name; v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks if(v != undefined && v !== false) attr[n] = v }) return attr } })(jQuery); 

用法:

 var attribs = $('#some_id').getAttributes(); 

安装员和Getter!

 (function($) { // Attrs $.fn.attrs = function(attrs) { var t = $(this); if (attrs) { // Set attributes t.each(function(i, e) { var j = $(e); for (var attr in attrs) { j.attr(attr, attrs[attr]); } }); return t; } else { // Get attributes var a = {}, r = t.get(0); if (r) { r = r.attributes; for (var i in r) { var p = r[i]; if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue; } } return a; } }; })(jQuery); 

使用:

 // Setter $('#element').attrs({ 'name' : 'newName', 'id' : 'newId', 'readonly': true }); // Getter var attrs = $('#element').attrs(); 

罗兰·布曼的答案是最好的,简单的香草方式。 我注意到了一些jQ插件的尝试,但对我来说似乎并不“足够”,所以我做了我自己的。 目前唯一的挫折是无法直接调用elm.attr('dynamicAttr')来访问dynamic添加的attrs。 但是,这将返回一个jQuery元素对象的所有自然属性。

插件使用简单的jQuery风格调用:

 $(elm).getAttrs(); // OR $.getAttrs(elm); 

你也可以添加第二个string参数来获取一个特定的attr。 这对于一个元素select并不是真的需要,因为jQuery已经提供了$(elm).attr('name') ,但是,我的插件版本允许多个返回。 所以,举个例子来说,

 $.getAttrs('*', 'class'); 

将导致数组[]返回对象{} 。 每个对象将如下所示:

 { class: 'classes names', elm: $(elm), index: i } // index is $(elm).index() 

插入

 ;;(function($) { $.getAttrs || ($.extend({ getAttrs: function() { var a = arguments, d, b; if (a.length) for (x in a) switch (typeof a[x]) { case "object": a[x] instanceof jQuery && (b = a[x]); break; case "string": b ? d || (d = a[x]) : b = $(a[x]) } if (b instanceof jQuery) { var e = []; if (1 == b.length) { for (var f = 0, g = b[0].attributes, h = g.length; f < h; f++) a = g[f], e[a.name] = a.value; b.data("attrList", e); d && "all" != d && (e = b.attr(d)) } else d && "all" != d ? b.each(function(a) { a = { elm: $(this), index: $(this).index() }; a[d] = $(this).attr(d); e.push(a) }) : b.each(function(a) { $elmRet = []; for (var b = 0, d = this.attributes, f = d.length; b < f; b++) a = d[b], $elmRet[a.name] = a.value; e.push({ elm: $(this), index: $(this).index(), attrs: $elmRet }); $(this).data("attrList", e) }); return e } return "Error: Cannot find Selector" } }), $.fn.extend({ getAttrs: function() { var a = [$(this)]; if (arguments.length) for (x in arguments) a.push(arguments[x]); return $.getAttrs.apply($, a) } })) })(jQuery); 

遵守

 ;;(function(c){c.getAttrs||(c.extend({getAttrs:function(){var a=arguments,d,b;if(a.length)for(x in a)switch(typeof a[x]){case "object":a[x]instanceof jQuery&&(b=a[x]);break;case "string":b?d||(d=a[x]):b=c(a[x])}if(b instanceof jQuery){if(1==b.length){for(var e=[],f=0,g=b[0].attributes,h=g.length;f<h;f++)a=g[f],e[a.name]=a.value;b.data("attrList",e);d&&"all"!=d&&(e=b.attr(d));for(x in e)e.length++}else e=[],d&&"all"!=d?b.each(function(a){a={elm:c(this),index:c(this).index()};a[d]=c(this).attr(d);e.push(a)}):b.each(function(a){$elmRet=[];for(var b=0,d=this.attributes,f=d.length;b<f;b++)a=d[b],$elmRet[a.name]=a.value;e.push({elm:c(this),index:c(this).index(),attrs:$elmRet});c(this).data("attrList",e);for(x in $elmRet)$elmRet.length++});return e}return"Error: Cannot find Selector"}}),c.fn.extend({getAttrs:function(){var a=[c(this)];if(arguments.length)for(x in arguments)a.push(arguments[x]);return c.getAttrs.apply(c,a)}}))})(jQuery); 

的jsfiddle

 /* BEGIN PLUGIN */ ;;(function($) { $.getAttrs || ($.extend({ getAttrs: function() { var a = arguments, c, b; if (a.length) for (x in a) switch (typeof a[x]) { case "object": a[x] instanceof f && (b = a[x]); break; case "string": b ? c || (c = a[x]) : b = $(a[x]) } if (b instanceof f) { if (1 == b.length) { for (var d = [], e = 0, g = b[0].attributes, h = g.length; e < h; e++) a = g[e], d[a.name] = a.value; b.data("attrList", d); c && "all" != c && (d = b.attr(c)); for (x in d) d.length++ } else d = [], c && "all" != c ? b.each(function(a) { a = { elm: $(this), index: $(this).index() }; a[c] = $(this).attr(c); d.push(a) }) : b.each(function(a) { $elmRet = []; for (var b = 0, c = this.attributes, e = c.length; b < e; b++) a = c[b], $elmRet[a.name] = a.value; d.push({ elm: $(this), index: $(this).index(), attrs: $elmRet }); $(this).data("attrList", d); for (x in $elmRet) $elmRet.length++ }); return d } return "Error: Cannot find Selector" } }), $.fn.extend({ getAttrs: function() { var a = [$(this)]; if (arguments.length) for (x in arguments) a.push(arguments[x]); return $.getAttrs.apply($, a) } })) })(jQuery); /* END PLUGIN */ /*--------------------*/ $('#bob').attr('bob', 'bill'); console.log($('#bob')) console.log(new Array(50).join(' -')); console.log($('#bob').getAttrs('id')); console.log(new Array(50).join(' -')); console.log($.getAttrs('#bob')); console.log(new Array(50).join(' -')); console.log($.getAttrs('#bob', 'name')); console.log(new Array(50).join(' -')); console.log($.getAttrs('*', 'class')); console.log(new Array(50).join(' -')); console.log($.getAttrs('p')); console.log(new Array(50).join(' -')); console.log($('#bob').getAttrs('all')); console.log($('*').getAttrs('all')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> All of below is just for stuff for plugin to test on. See developer console for more details. <hr /> <div id="bob" class="wmd-button-bar"><ul id="wmd-button-row-27865269" class="wmd-button-row" style="display:none;"> <div class="post-text" itemprop="text"> <p>Roland Bouman's answer is the best, simple Vanilla way. I noticed some attempts at jQ plugs, but they just didn't seem "full" enough to me, so I made my own. The only setback so far has been inability to access dynamically added attrs without directly calling <code>elm.attr('dynamicAttr')</code>. However, this will return all natural attributes of a jQuery element object.</p> <p>Plugin uses simple jQuery style calling:</p> <pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">).</span><span class="pln">getAttrs</span><span class="pun">();</span><span class="pln"> </span><span class="com">// OR</span><span class="pln"> $</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">);</span></code></pre> <p>You can also add a second string param for getting just one specific attr. This isn't really needed for one element selection, as jQuery already provides <code>$(elm).attr('name')</code>, however, my version of a plugin allows for multiple returns. So, for instance, a call like</p> <pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="str">'*'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'class'</span><span class="pun">);</span></code></pre> <p>Will result in an array <code>[]</code> return of objects <code>{}</code>. Each object will look like:</p> <pre class="default prettyprint prettyprinted"><code><span class="pun">{</span><span class="pln"> </span><span class="kwd">class</span><span class="pun">:</span><span class="pln"> </span><span class="str">'classes names'</span><span class="pun">,</span><span class="pln"> elm</span><span class="pun">:</span><span class="pln"> $</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">),</span><span class="pln"> index</span><span class="pun">:</span><span class="pln"> i </span><span class="pun">}</span><span class="pln"> </span><span class="com">// index is $(elm).index()</span></code></pre> </div> </div> 

如果您需要获取数组中返回的对象中的名称和值的所有属性,则此方法可以很好地工作。

示例输出:

 [ { name: 'message', value: 'test2' } ... ] 
 function getElementAttrs(el) { return [].slice.call(el.attributes).map((attr) => { return { name: attr.name, value: attr.value } }); } var allAttrs = getElementAttrs(document.querySelector('span')); console.log(allAttrs); 
 <span name="test" message="test2"></span> 

使用.sliceattributes转换为数组

DOM节点的attributes属性是一个NamedNodeMap ,它是一个类似于数组的对象。

一个类似于数组的对象是一个具有length属性并且其属性名被枚举的对象,但是除此之外,它有自己的方法并且不能从Array.prototypeinheritance

slice方法可用于将类似数组的对象转换为新的数组 。

 var elem = document.querySelector('[name=test]').attributes, attrs = Array.prototype.slice.call(elem); console.log(attrs); 
 <span name="test" message="test2">Open your console.</span> 

这有帮助吗?

这个属性为你返回一个元素的所有属性到一个数组中。 这是一个例子。

 window.addEventListener('load', function() { var result = document.getElementById('result'); var spanAttributes = document.getElementsByTagName('span')[0].attributes; for (var i = 0; i != spanAttributes.length; i++) { result.innerHTML += spanAttributes[i].value + ','; } }); 
 <span name="test" message="test2"></span> <div id="result"></div> 

从html获取属性

 <button data-createdbyid="MyId" onclick="myFunction($event)">Click me</button> 

然后在javascript中:

 function myFunction(event) { var CreatedById = $(event.currentTarget).attr('data-createdbyid'); //or var CreatedById2 = $(event.currentTarget).data('createdbyid'); //do something with that... } 

祝你好运!

更简洁的方法来做到这一点:

旧的方式(IE9 +):

 var element = document.querySelector(/* … */); [].slice.call(element.attributes).map(function (attr) { return attr.nodeName; }); 

ES6方式(Edge 12+):

 [...document.querySelector(/* … */).attributes].map(attr => attr.nodeName); 
  • document.querySelector()返回文档中与指定select器相匹配的第一个元素 。
  • Element.attributes返回一个NamedNodeMap对象,该对象包含相应HTML元素的指定属性。
  • [].map()创build一个新的数组,并在调用数组中的每个元素上调用提供的函数。

演示:

 console.log( [...document.querySelector('img').attributes].map(attr => attr.nodeName) ); 
 /* Output console formatting */ .as-console-wrapper { position: absolute; top: 0; } 
 <img src="…" alt="…" height="…" width="…"/> 

如果您只需要查看所有属性, 尝试console.dir()

 console.dir(myElement); 

在javascript中:

 var attributes; var spans = document.getElementsByTagName("span"); for(var s in spans){ if (spans[s].getAttribute('name') === 'test') { attributes = spans[s].attributes; break; } } 

要访问属性名称和值:

 attributes[0].nodeName attributes[0].nodeValue