Получить все атрибуты из HTML-элемента с помощью Javascript/jQuery
Я хочу поместить все атрибуты в элемент Html в массив:
например, у меня есть объект jQuery, который html выглядит следующим образом:
<span name="test" message="test2"></span>
теперь один способ - использовать синтаксический анализатор xml, описанный здесь здесь, но тогда мне нужно знать, как получить html-код моего объекта.
Другой способ сделать это с помощью jquery, но как?
количество атрибутов и имена являются общими.
Спасибо
Btw: я не могу получить доступ к элементу с document.getelementbyid или что-то подобное.
Ответы
Ответ 1
Если вам просто нужны атрибуты DOM, возможно, проще использовать список attributes
node для самого элемента:
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);
}
Ответ 2
Вы можете использовать этот простой плагин как $('# 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
Простой:
var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
Ответ 4
Потому что в IE7 elem.attributes перечислены все возможные атрибуты, а не только настоящие, мы должны проверить значение атрибута.
Этот плагин работает во всех основных браузерах:
(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();
Ответ 5
Сеттер и 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();
Ответ 6
Роланд Буман answer - лучший, простой ванильский путь. Я заметил некоторые попытки подключений jQ, но они просто не казались мне "полными", поэтому я сделал свой собственный. Единственным препятствием на данный момент является невозможность доступа к динамически добавленным attrs без прямого вызова elm.attr('dynamicAttr')
. Тем не менее, это вернет все естественные атрибуты элемента элемента jQuery.
Плагин использует простой вызов стиля jQuery:
$(elm).getAttrs();
// OR
$.getAttrs(elm);
Вы также можете добавить второй параметр строки для получения только одного определенного attr. Это действительно не требуется для выбора одного элемента, поскольку jQuery уже предоставляет $(elm).attr('name')
, однако моя версия плагина допускает несколько возвратов. Так, например, вызов типа
$.getAttrs('*', 'class');
В результате массив []
возвращает объекты {}
. Каждый объект будет выглядеть так:
{ 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);
Выполнено
;;(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);
/* 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 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>
Ответ 7
Этот подход хорошо работает, если вам нужно получить все атрибуты с именем и значением в объектах, возвращаемых в массиве.
Пример вывода:
[
{
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>
Ответ 8
Используйте .slice
для преобразования свойства attributes
в Array
Свойство attributes
для узлов DOM - это NamedNodeMap
, который является объектом типа Array.
Объект, подобный массиву, представляет собой объект, который имеет свойство length
и имена свойств которого перечислены, но в остальном имеет свои собственные методы и не наследует от Array.prototype
Метод slice
может использоваться для преобразования объектов, подобных Array, в новый массив.
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>
Ответ 9
Помогает ли это?
Это свойство возвращает все атрибуты элемента в массив для вас. Вот пример.
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>
Ответ 10
Чтобы получить свойство из 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...
}
Удачи!
Ответ 11
Гораздо более сжатые способы сделать это:
Старый способ (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);
Демо:
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
Если вам просто нужно видеть все атрибуты, попробуйте console.dir()
.
console.dir(myElement);
Ответ 13
В 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