valor tiene saber obtener elemento con cambiar atributo agregar javascript jquery attributes parsing

tiene - setattribute javascript



Obtenga todos los atributos de un elemento HTML con Javascript/jQuery (12)

Quiero poner todos los atributos en un elemento Html en una matriz: como si tuviera un Objeto jQuery, cuyo html tiene este aspecto:

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

ahora una forma es usar el analizador xml descrito here , pero luego necesito saber cómo obtener el código html de mi objeto.

la otra forma es hacerlo con jquery, pero ¿cómo? el número de atributos y los nombres son genéricos.

Gracias

Por cierto: no puedo acceder al elemento con document.getelementbyid o algo similar.


Use .slice para convertir la propiedad de attributes a Array

La propiedad de attributes de los nodos DOM es un NamedNodeMap , que es un objeto tipo Array.

Un objeto tipo Array es un objeto que tiene una propiedad de length y cuyos nombres de propiedad están enumerados, pero tiene sus propios métodos y no hereda de Array.prototype

El método de slice se puede usar para convertir objetos similares a Array en una nueva matriz .

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>


¡Setter y 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);

Utilizar:

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


¿Esto ayuda?

Esta propiedad devuelve todos los atributos de un elemento en una matriz. Aquí hay un ejemplo.

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>

Para obtener los atributos de muchos elementos y organizarlos, sugiero hacer una matriz de todos los elementos que desee recorrer y luego crear una matriz secundaria para todos los atributos de cada elemento en el que se haya realizado un bucle.

Este es un ejemplo de una secuencia de comandos que recorrerá los elementos recopilados e imprimirá dos atributos. Este script asume que siempre habrá dos atributos, pero puede arreglarlo fácilmente con un mapeo adicional.

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>


En javascript:

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

Para acceder a los nombres y valores de los atributos:

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


Este enfoque funciona bien si necesita obtener todos los atributos con nombre y valor en los objetos devueltos en una matriz.

Ejemplo de salida:

[ { 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 solo desea una matriz de nombres de atributos para ese elemento, puede asignar los resultados:

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


Formas mucho más concisas de hacerlo:

A la antigua (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() devuelve el primer Element dentro del documento que coincide con el selector especificado.
  • Element.attributes devuelve un objeto NamedNodeMap que contiene los atributos asignados del elemento HTML correspondiente.
  • [].map() crea una nueva matriz con los resultados de llamar a una función proporcionada en cada elemento de la matriz llamante.

Manifestación:

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


La answer es la mejor y más simple forma de Vanilla. Observé algunos intentos de enchufes jQ, pero no me parecían lo suficientemente "completos", así que hice los míos. El único revés hasta el momento ha sido la imposibilidad de acceder attrs agregados dinámicamente sin llamar directamente a elm.attr(''dynamicAttr'') . Sin embargo, esto devolverá todos los atributos naturales de un objeto de elemento jQuery.

El complemento usa llamadas de estilo jQuery simples:

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

También puede agregar un segundo param de cadena para obtener solo un atributo específico. Esto no es realmente necesario para la selección de un elemento, ya que jQuery ya proporciona $(elm).attr(''name'') , sin embargo, mi versión de un complemento permite múltiples devoluciones. Entonces, por ejemplo, una llamada como

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

Provocará una matriz [] retorno de objetos {} . Cada objeto se verá así:

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

Enchufar

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

Cumplido

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


Para obtener una propiedad de html

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

y luego en javascript:

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

¡Buena suerte!


Porque en IE7 elem.attributes enumera todos los atributos posibles, no solo los actuales, tenemos que probar el valor del atributo. Este complemento funciona en todos los principales navegadores:

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

Uso:

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


Puede usar este complemento simple como $ (''# 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);


Sencillo:

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


Si solo desea los atributos DOM, probablemente sea más sencillo usar la lista de nodos de attributes en el elemento mismo:

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

Tenga en cuenta que esto llena la matriz solo con nombres de atributos. Si necesita el valor del atributo, puede usar la propiedad 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); }