web-dev-qa-db-fra.com

Obtenir tous les attributs d'un élément HTML avec Javascript/jQuery

Je veux mettre tous les attributs d'un élément HTML dans un tableau: Comme si j'avais un objet jQuery, dont le code HTML ressemble à ceci:

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

une solution consiste maintenant à utiliser l’analyseur XML décrit ici , mais j’ai besoin de savoir comment obtenir le code html de mon objet.

l’autre méthode consiste à utiliser jquery, mais comment? le nombre d’attributs et les noms sont génériques.

Merci

Btw: Je ne peux pas accéder à l'élément avec document.getelementbyid ou quelque chose de similaire.

156
k0ni

Si vous voulez juste les attributs DOM, il est probablement plus simple d'utiliser la liste de noeuds attributes sur l'élément lui-même:

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

Notez que cela remplit le tableau uniquement avec des noms d'attributs. Si vous avez besoin de la valeur d'attribut, vous pouvez utiliser la propriété 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);
}
196
Roland Bouman

Vous pouvez utiliser ce simple plugin en tant que $ ('# 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);
70
manRo

Simple:

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

Parce que dans IE7, elem.attributes répertorie tous les attributs possibles, pas seulement ceux actuels, nous devons tester la valeur de l'attribut .

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

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

Utilisation:

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

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

Utilisez .slice pour convertir la propriété attributes en tableau

La propriété attributes des noeuds DOM est un NamedNodeMap , qui est un objet de type tableau.

Un objet semblable à un tableau est un objet qui a une propriété length et dont les noms de propriété sont énumérés, mais qui a ses propres méthodes et n'hérite pas de Array.prototype

La méthode slice peut être utilisée pour convertir des objets de type tableau en un nouveau tableau .

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

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

6
gfullam

Cette approche fonctionne bien si vous devez obtenir tous les attributs avec le nom et la valeur dans les objets renvoyés dans un tableau.

Exemple de sortie:

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

Si vous souhaitez uniquement un tableau de noms d'attributs pour cet élément, vous pouvez simplement mapper les résultats:

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

Roland Bouman 's answer est la meilleure façon simple de vanille. J'ai remarqué quelques tentatives de jQ plugs, mais ils ne m'ont pas semblé suffisamment "pleins", alors j'ai créé le mien. Jusqu'à présent, le seul inconvénient a été l'incapacité d'accéder à des attrs ajoutés de manière dynamique sans appeler directement Elm.attr('dynamicAttr'). Cependant, cela renverra tous les attributs naturels d'un objet d'élément jQuery.

Le plugin utilise des appels de style jQuery simples:

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

Vous pouvez également ajouter un deuxième paramètre de chaîne pour obtenir un seul attr. Cela n'est pas vraiment nécessaire pour la sélection d'un élément, car jQuery fournit déjà $(Elm).attr('name'). Cependant, ma version d'un plugin autorise plusieurs retours. Ainsi, par exemple, un appel comme

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

Entraînera un retour de tableau [] d'objets {}. Chaque objet ressemblera à:

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

Brancher

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

Conforme

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

2
SpYk3HH

Des façons beaucoup plus concises de le faire:

Ancienne manière (IE9 +):

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

Voie ES6 (Edge 12+):

[...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
  • document.querySelector() retourne le premier élément du document correspondant au sélecteur spécifié.
  • Element.attributes retourne un NamedNodeMap object contenant les attributs attribués à l'élément HTML correspondant.
  • [].map() crée un nouveau tableau avec les résultats de l'appel d'une fonction fournie sur chaque élément du tableau appelant.

Démo:

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

1
Przemek

Est-ce que cela aide?

Cette propriété renvoie tous les attributs d'un élément dans un tableau pour vous. Voici un exemple.

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>

Pour obtenir les attributs de nombreux éléments et les organiser, nous vous suggérons de créer un tableau de tous les éléments que vous souhaitez parcourir, puis de créer un sous-tableau pour tous les attributs de chaque élément.

Voici un exemple de script qui parcourt les éléments collectés et affiche deux attributs. Ce script suppose qu'il y aura toujours deux attributs, mais vous pouvez facilement résoudre ce problème avec un mappage supplémentaire.

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>

1
www139

Ici, chaque réponse manque à la solution la plus simple utilisant la méthode getAttributeNames element!

Il récupère les noms de tous les attributs actuels de l'élément sous forme de tableau standard, que vous pouvez ensuite réduire à un objet Nice de clés/valeurs.

const getAllAttributes = el => el
  .getAttributeNames()
  .reduce((obj, name) => ({
    ...obj,
    [name]: el.getAttribute(name)
  }), {})

console.log(getAllAttributes(document.querySelector('div')))
<div title="hello" className="foo" data-foo="bar"></div>

0
Tim Kindberg
Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

ayant <div id="mydiv" a='1' b='2'>...</div> peut utiliser

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}
0
bortunac

Essayez quelque chose comme ça

    <div id=foo [href]="url" class (click)="alert('hello')" data-hello=world></div>

et ensuite obtenir tous les attributs

    const foo = document.getElementById('foo');
    // or if you have a jQuery object
    // const foo = $('#foo')[0];

    function getAttributes(el) {
        const attrObj = {};
        if(!el.hasAttributes()) return attrObj;
        for (const attr of el.attributes)
            attrObj[attr.name] = attr.value;
        return attrObj
    }

    // {"id":"foo","[href]":"url","class":"","(click)":"alert('hello')","data-hello":"world"}
    console.log(getAttributes(foo));

pour tableau d'attributs utiliser 

    // ["id","[href]","class","(click)","data-hello"]
    Object.keys(getAttributes(foo))
0
weroro

Imaginez que vous ayez un élément HTML comme ci-dessous:

<a class="toc-item"
   href="/books/n/ukhta2333/s5/"
   id="book-link-29"
>
   Chapter 5. Conclusions and recommendations
</a>

Une façon dont vous pouvez obtenir tous les attributs consiste à les convertir en tableau:

const el = document.getElementById("book-link-29")
const attrArray = Array.from(el.attributes)

// Now you can iterate all the attributes and do whatever you need.
const attributes = attrArray.reduce((attrs, attr) => {
    attrs !== '' && (attrs += ' ')
    attrs += `${attr.nodeName}="${attr.nodeValue}"`
    return attrs
}, '')
console.log(attributes)

Et ci-dessous est la chaîne que vous obtiendrez (de l'exemple), qui comprend tous les attributs:

class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"
0
Yuci