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

时间:2022-08-27 12:32:53

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:

我想将Html元素中的所有属性都放到一个数组中:比如我有一个jQuery对象,它的Html是这样的:

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

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

the other way is to make it with jquery, but how? the number of attributes and the names are generic.

另一种方法是使用jquery,但是如何实现呢?属性的数量和名称是通用的。

Thanks

谢谢

Btw: I can't access the element with document.getelementbyid or something similar.

我不能用文档来访问元素。getelementbyid或类似的东西。

12 个解决方案

#1


188  

If you just want the DOM attributes, it's probably simpler to use the attributes node list on the element itself:

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

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:

注意,这只填充了属性名称的数组。如果需要属性值,可以使用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);
}

#2


69  

You can use this simple plugin as $('#some_id').getAttributes();

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

#3


54  

Simple:

简单:

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

#4


19  

Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:

因为在IE7 elem。属性列出所有可能的属性,而不仅仅是当前属性,我们必须测试属性值。这个插件适用于所有主流浏览器:

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

Usage:

用法:

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

#5


18  

Setter and Getter!

Setter和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);

Use:

使用:

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

// Getter
var attrs = $('#element').attrs();

#6


3  

Use .slice to convert the attributes property to Array

The attributes property of DOM nodes is a NamedNodeMap, which is an Array-like object.

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

An Array-like object is an object which has a length property and whose property names are enumerated, but otherwise has its own methods and does not inherit from Array.prototype

类数组对象是一个具有长度属性和属性名称的对象,但是它有自己的方法,并且不继承Array.prototype。

The slice method can be used to convert Array-like objects to a new Array.

切片方法可用于将arraylike对象转换为新数组。

var elem  = document.querySelector('[name=test]'),
    attrs = Array.prototype.slice.call(elem.attributes);

console.log(attrs);
<span name="test" message="test2">Open your console.</span>

#7


2  

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 elm.attr('dynamicAttr'). However, this will return all natural attributes of a jQuery element object.

罗兰·布曼的回答是最好的,简单的香草的方法。我注意到一些jQ插头的尝试,但是它们看起来不够“满”,所以我自己做了。到目前为止,唯一的挫折是无法在不直接调用elm.attr(“dynamicAttr”)的情况下动态添加attrs。但是,这将返回jQuery元素对象的所有自然属性。

Plugin uses simple jQuery style calling:

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

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

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 $(elm).attr('name'), however, my version of a plugin allows for multiple returns. So, for instance, a call like

您还可以添加第二个字符串param来获得一个特定的attr。这并不需要一个元素的选择,因为jQuery已经提供了$(elm).attr('name'),但是,我的版本的插件允许多重返回。比如,一个电话。

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

Will result in an array [] return of objects {}. Each object will look like:

将会导致数组[]返回对象{}。每个对象看起来如下:

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

Plugin

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

Complied

;;(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>

#8


2  

This approach works well if you need to get all the attributes with name and value in objects returned in an array.

如果需要以数组中返回的对象的名称和值来获取所有属性,那么这种方法很有效。

Example output:

示例输出:

[
    {
        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>

If you want only an array of attribute names for that element, you can just map the results:

如果您只需要该元素的属性名数组,您可以只映射结果:

var onlyAttrNames = allAttrs.map(attr => attr.name);
console.log(onlyAttrNames); // ["name", "message"]

#9


0  

Does this help?

这有帮助吗?

This property returns all the attributes of an element into an array for you. Here is an example.

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

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>

To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.

为了获得许多元素的属性并组织它们,我建议创建一个所有元素的数组,这些元素都是您想要循环的,然后为每个元素的所有属性创建一个子数组。

This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.

这是一个脚本示例,它将遍历所收集的元素并打印出两个属性。这个脚本假定总是有两个属性,但是您可以通过进一步的映射轻松地修复它。

window.addEventListener('load',function(){
  /*
  collect all the elements you want the attributes
  for into the variable "elementsToTrack"
  */ 
  var elementsToTrack = $('body span, body div');
  //variable to store all attributes for each element
  var attributes = [];
  //gather all attributes of selected elements
  for(var i = 0; i != elementsToTrack.length; i++){
    var currentAttr = elementsToTrack[i].attributes;
    attributes.push(currentAttr);
  }
  
  //print out all the attrbute names and values
  var result = document.getElementById('result');
  for(var i = 0; i != attributes.length; i++){
    result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div id="result"></div>

#10


0  

To get a property from html

从html获取属性。

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

and then in javascript:

然后在javascript中:

function myFunction(event) {

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

Good luck!

好运!

#11


0  

Much more concise ways to do it:

更简明的方法是:

Old way (IE9+):

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

ES6 way (Edge 12+):

[...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
  • document.querySelector() returns the first Element within the document that matches the specified selector.
  • document.querySelector()返回与指定选择器匹配的文档中的第一个元素。
  • Element.attributes returns a NamedNodeMap object containing the assigned attributes of the corresponding HTML element.
  • 元素。属性返回一个NamedNodeMap对象,该对象包含相应HTML元素的指定属性。
  • [].map() creates a new array with the results of calling a provided function on every element in the calling array.
  • map()创建一个新的数组,其结果是调用调用数组中的每个元素的函数。

Demo:

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="…"/>

#12


-6  

In javascript:

在javascript中:

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

To access the attributes names and values:

访问属性名称和值:

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

#1


188  

If you just want the DOM attributes, it's probably simpler to use the attributes node list on the element itself:

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

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:

注意,这只填充了属性名称的数组。如果需要属性值,可以使用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);
}

#2


69  

You can use this simple plugin as $('#some_id').getAttributes();

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

#3


54  

Simple:

简单:

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

#4


19  

Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:

因为在IE7 elem。属性列出所有可能的属性,而不仅仅是当前属性,我们必须测试属性值。这个插件适用于所有主流浏览器:

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

Usage:

用法:

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

#5


18  

Setter and Getter!

Setter和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);

Use:

使用:

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

// Getter
var attrs = $('#element').attrs();

#6


3  

Use .slice to convert the attributes property to Array

The attributes property of DOM nodes is a NamedNodeMap, which is an Array-like object.

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

An Array-like object is an object which has a length property and whose property names are enumerated, but otherwise has its own methods and does not inherit from Array.prototype

类数组对象是一个具有长度属性和属性名称的对象,但是它有自己的方法,并且不继承Array.prototype。

The slice method can be used to convert Array-like objects to a new Array.

切片方法可用于将arraylike对象转换为新数组。

var elem  = document.querySelector('[name=test]'),
    attrs = Array.prototype.slice.call(elem.attributes);

console.log(attrs);
<span name="test" message="test2">Open your console.</span>

#7


2  

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 elm.attr('dynamicAttr'). However, this will return all natural attributes of a jQuery element object.

罗兰·布曼的回答是最好的,简单的香草的方法。我注意到一些jQ插头的尝试,但是它们看起来不够“满”,所以我自己做了。到目前为止,唯一的挫折是无法在不直接调用elm.attr(“dynamicAttr”)的情况下动态添加attrs。但是,这将返回jQuery元素对象的所有自然属性。

Plugin uses simple jQuery style calling:

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

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

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 $(elm).attr('name'), however, my version of a plugin allows for multiple returns. So, for instance, a call like

您还可以添加第二个字符串param来获得一个特定的attr。这并不需要一个元素的选择,因为jQuery已经提供了$(elm).attr('name'),但是,我的版本的插件允许多重返回。比如,一个电话。

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

Will result in an array [] return of objects {}. Each object will look like:

将会导致数组[]返回对象{}。每个对象看起来如下:

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

Plugin

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

Complied

;;(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>

#8


2  

This approach works well if you need to get all the attributes with name and value in objects returned in an array.

如果需要以数组中返回的对象的名称和值来获取所有属性,那么这种方法很有效。

Example output:

示例输出:

[
    {
        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>

If you want only an array of attribute names for that element, you can just map the results:

如果您只需要该元素的属性名数组,您可以只映射结果:

var onlyAttrNames = allAttrs.map(attr => attr.name);
console.log(onlyAttrNames); // ["name", "message"]

#9


0  

Does this help?

这有帮助吗?

This property returns all the attributes of an element into an array for you. Here is an example.

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

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>

To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.

为了获得许多元素的属性并组织它们,我建议创建一个所有元素的数组,这些元素都是您想要循环的,然后为每个元素的所有属性创建一个子数组。

This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.

这是一个脚本示例,它将遍历所收集的元素并打印出两个属性。这个脚本假定总是有两个属性,但是您可以通过进一步的映射轻松地修复它。

window.addEventListener('load',function(){
  /*
  collect all the elements you want the attributes
  for into the variable "elementsToTrack"
  */ 
  var elementsToTrack = $('body span, body div');
  //variable to store all attributes for each element
  var attributes = [];
  //gather all attributes of selected elements
  for(var i = 0; i != elementsToTrack.length; i++){
    var currentAttr = elementsToTrack[i].attributes;
    attributes.push(currentAttr);
  }
  
  //print out all the attrbute names and values
  var result = document.getElementById('result');
  for(var i = 0; i != attributes.length; i++){
    result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<span name="test" message="test2"></span>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div name="test" message="test2"></div>
<div id="result"></div>

#10


0  

To get a property from html

从html获取属性。

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

and then in javascript:

然后在javascript中:

function myFunction(event) {

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

Good luck!

好运!

#11


0  

Much more concise ways to do it:

更简明的方法是:

Old way (IE9+):

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

ES6 way (Edge 12+):

[...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
  • document.querySelector() returns the first Element within the document that matches the specified selector.
  • document.querySelector()返回与指定选择器匹配的文档中的第一个元素。
  • Element.attributes returns a NamedNodeMap object containing the assigned attributes of the corresponding HTML element.
  • 元素。属性返回一个NamedNodeMap对象,该对象包含相应HTML元素的指定属性。
  • [].map() creates a new array with the results of calling a provided function on every element in the calling array.
  • map()创建一个新的数组,其结果是调用调用数组中的每个元素的函数。

Demo:

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="…"/>

#12


-6  

In javascript:

在javascript中:

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

To access the attributes names and values:

访问属性名称和值:

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