javascript - ¿Cómo obtener elementos por atributo cuando querySelectorAll no está disponible sin usar bibliotecas?
<p data-foo="bar">
¿Cómo puedes hacer lo equivalente a
document.querySelectorAll('[data-foo]')
¿Dónde no está disponible querySelectorAll?
Necesito una solución nativa que funcione al menos en IE7. No me importa IE6.
Respuesta #1
Podrías escribir una función que ejecute getElementsByTagName('*'), y devuelva solo aquellos elementos con un atributo "data-foo":
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
Entonces,
getAllElementsWithAttribute('data-foo');
Respuesta #2
Usar
//find first element with "someAttr" attribute
document.querySelector('[someAttr]')
o
//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]')
para encontrar elementos por atributo. Ahora es compatible en todos los navegadores relevantes (incluso IE8): http://caniuse.com/#search=queryselector
Respuesta #3
Jugué un poco y terminé con esta solución rudimentaria:
function getElementsByAttribute(attribute, context) {
var nodeList = (context || document).getElementsByTagName('*');
var nodeArray = [];
var iterator = 0;
var node = null;
while (node = nodeList[iterator++]) {
if (node.hasAttribute(attribute)) nodeArray.push(node);
}
return nodeArray;
}
El uso es bastante simple, y funciona incluso en IE8:
getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);
http://fiddle.jshell.net/9xaxf6jr/
Pero yo recomiendo usar querySelector/All para esto (y para soportar navegadores más antiguos usar un polyfill):
document.querySelectorAll('[data-foo]');
Respuesta #4
Prueba esto, funciona
document.querySelector('[attribute="value"]')
ejemplo :
document.querySelector('[role="button"]')
